Formating Numbers with Commas

Actionscript:
  1. trace(formatNum(1000));
  2. trace(formatNum(10000000));
  3. trace(formatNum(1000000.39485));
  4.  
  5. function formatNum(num:Number):String {
  6.     var newStr:String = "";
  7.     var str:String = num.toString();
  8.    
  9.     var parts:Array = str.split(".");
  10.     str = parts[0];
  11.     var end:String = (parts[1]) ? "." + parts[1] : "";
  12.    
  13.     var i:int = str.length;
  14.     while(i--> 0){
  15.          var char:String = str.charAt(i);
  16.          if ((str.length - i) % 3 == 0){
  17.             newStr = "," + char +newStr;
  18.          }else{
  19.             newStr = char +  newStr;
  20.          }
  21.     }
  22.     return newStr + end;
  23. }
  24. /*
  25. outputs:
  26. 1,000
  27. 10,000,000
  28. 1,000,000.39485
  29. */

The function formatNum() returns a string given a number argument ... it adds commas where appropriate and takes into account decimal values. This is useful anywhere you need to display numbers over 1,000, in a game, in a calculator app etc...

This entry was posted in string manipulation and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*