function PadDecimals(num, decimal_places) {
  // pad decimal_places?
  if (decimal_places == '0') {
    // return integer part
    return parseInt(num);
  } else {
    // cast as string
    num = num + '';
    
    // get decimal part
    var dec = num.substr((num.indexOf('.')+1));
    
    // if no decimal part, set to 0
    if (num.indexOf('.') == -1) {
      dec = '0';
    }
    
    // pad
    while (dec.length < decimal_places) {
      dec += '0';
    }
    
    // put it all together
    str = parseInt(num) + "." + dec.substr(0, decimal_places);
    
    // return padded number
    return str;
  }
}

function CleanNumber(num) {
  // strip off non digits
  var regex = /[^-.0-9]/g;
  val = new String(num);
  val = val.replace(regex, '');
  return val;
}

function AddCommas(num) {
  num = num + '';
  if (isNaN(num) || num == '') {
    num = 0;
  } else {
    var regex = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
    arrNumber = num.split('.');
    arrNumber[0] += '.';
    do {
      arrNumber[0] = arrNumber[0].replace(regex, '$1,$2');
    } while (regex.test(arrNumber[0]));
    
    if (arrNumber.length > 1) {
      num = arrNumber.join('');
    } else {
      num = arrNumber[0].split('.')[0];
    }
  }
  
  return num;
}

function FormatNumber(num, decimal_places) {
  // only if decimal places
  if (decimal_places > 0) {
    // round number
    num = RoundNumber(num, decimal_places);
    
    // pad to decimal places
    num = PadDecimals(num, decimal_places);
  }
  
  return AddCommas(num);
}

function FormatCurrency(amount) {
  amount = CleanNumber(amount);
  var i = parseFloat(amount);
  if (isNaN(i)) { i = 0.00; }
  
	var minus = '';
	if (i < 0) { minus = '-'; }
  
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
  
	return '$' + AddCommas(s);
}

function ShiftRight(theNumber, k) {
	if (k == 0) {
    return (theNumber);
	} else {
		var k2 = 1;
		var num = k;
		if (num < 0) {
      num = -num;
    }
		for (var i = 1; i <= num; i++) {
			k2 = k2*10;
		}
	}
  
	if (k>0) {
    return(k2*theNumber);
  } else {
    return(theNumber/k2);
  }
}

function RoundSigDig(theNumber, numDigits) {
	with (Math) {
    if (theNumber == 0) {
      return(0);
		} else if(abs(theNumber) < 0.000000000001) {
      return(0);
		} else { // warning: ignores numbers less than 10^(-12)
			var k  = floor(log(abs(theNumber))/log(10))-numDigits;
			var k2 = ShiftRight(round(ShiftRight(abs(theNumber),-k)),k);
			if (theNumber > 0) {
        return(k2);
			} else {
        return(-k2);
      }
	  }
  }
}

function RoundNumber(num, decimal_places) {
  // only if decimal places
  if (decimal_places > 0) {
    num = Math.round(num * Math.pow(10, decimal_places)) / Math.pow(10, decimal_places);
  } else {
    num = Math.round(num);
  }
  
  return (num);
}
