Wednesday, August 6, 2008

Formatting numbers

This one comes up a lot - how to format a number with commas and decimal points? Just pass your number into this function and it will return a formatted string. Including commas is optional.

function formatNumbers(num:Number, comma:Boolean):String {
 // return a zero value if num is not valid
 if (isNaN(num)) {
  return "0.00";
 }
 // round num to the nearest 100th   
 num = Math.round(num * 100) / 100;
 // convert num to a string
 var num_str:String = String(num);
 // seperate any decimals from the whole numbers
 var num_array = num_str.split(".");
 // if there are no decimals add them using "00"
 if (num_array[1] == undefined) {
  num_array[1] = "00";
 }
 // if the decimals are too short, add an extra "0"   
 if (num_array[1].length == 1) {
  num_array[1] += "0";
 }
 // separate whole numbers with commas  
 // if required (comma = true)
 if (comma) {
  var whole_array:Array = new Array();
  var start:Number;
  var end:Number = num_array[0].length;
  while (end > 0) {
   start = Math.max(end - 3, 0);
   whole_array.unshift(num_array[0].slice(start, end));
   end = start;
  }
  num_array[0] = whole_array.join(",");
 }
 // construct a return string joining  
 // the whole numbers with the decimals
 return (num_array.join("."));
}
trace(formatNumbers(1234));
// outputs 1234.00
trace(formatNumbers(1234.56));
// outputs 1234.56
trace(formatNumbers(1234.5, true));
// outputs 1,234.50
trace(formatNumbers(-1234.56789, true));
// outputs -1,234.57

3 comments:

Anonymous said...

This works great! Thanks!

glosrfc said...

No problem...glad you found it useful!

Anonymous said...

neat! thx!