Skip to content

Instantly share code, notes, and snippets.

@40
Created July 2, 2012 05:42
Show Gist options
  • Select an option

  • Save 40/3031303 to your computer and use it in GitHub Desktop.

Select an option

Save 40/3031303 to your computer and use it in GitHub Desktop.
Formatting Numbers with Commas Function (Actionscript 3)
trace(formatNum(1000));
trace(formatNum(10000000));
trace(formatNum(1000000.39485));
 
function formatNum(num:Number):String {
    var newStr:String = "";
    var str:String = num.toString();
   
    var parts:Array = str.split(".");
    str = parts[0];
    var end:String = (parts[1]) ? "." + parts[1] : "";
   
    var i:int = str.length;
    while(i--> 0){
         var char:String = str.charAt(i);
         if ((str.length - i) % 3 == 0){
            newStr = "," + char +newStr;
         }else{
            newStr = char +  newStr;
         }
    }
    return newStr + end;
}
/*
outputs:
1,000
10,000,000
1,000,000.39485
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment