Posted By

adrianparr on 01/26/10


Tagged

number format String comma Decial Thousands Places


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

TrentSkunk


Format a Number to a String - With decimals and thousands separator


 / Published in: ActionScript 3
 

Format a number so it is more humanly readable. It allows for setting the number of decimal places (inc. adding 0000s to the end) and separating thousands with a comma.

Example usage:

trace(numberFormat(1234.695, 2, true, false)); // Output: 1,234.70

trace(numberFormat(16000000, 0, false, false)); // Output: 16,000,000

  1. function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
  2. {
  3.     var i:int = 0;
  4. var inc:Number = Math.pow(10, maxDecimals);
  5. var str:String = String(Math.round(inc * Number(number))/inc);
  6.      var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
  7.      var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
  8.      if (forceDecimals) {
  9. for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
  10. }
  11.      while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
  12.      return str.substr(0, sep - i) + ret;
  13. }

Report this snippet  

You need to login to post a comment.