Thursday, May 5, 2011

Number formatting in javascript

Javascript sucks when it comes to number formatting. The only inbuilt function is toFixed(n) that shows n decimal places in a floating-point number.

Here is a small function to format a javascript number using the thousands separator:
function addCommas(arg){
  if (typeof(arg) == "number")
    arg = String(arg);
  var x = arg.split("."); 
  var characteristic = x[0];  
  var dotAndMantissa = x.length > 1 ? "." + x[1] : "";
  characteristic = characteristic.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
  return characteristic + dotAndMantissa;
}
It simply splits the number into the characteristic(the part before the decimal separator) and the mantissa(the part after the decimal), adds commas after every third digit starting from the right to the characteristic, suffixes the mantissa back, and returns the formatted string.

No comments:

Post a Comment