CGI Interactions
A blog about interactive communications for marketers, designers and developers

Formatting Numbers With Commas in AS3

May 15th, 2009 . by nixon

1000 or 1,000? The number is pretty easy to decipher regardless, so get off my back about the commas, right? How about 1000000 or 10000000? This is where the sweet, sweet comma can really come in handy.

Recently we built an opportunity assessment calculator for a client. The tool allowed our client’s sales force to work with retail managers and determine how they could increase profitability with their e-commerce enabled website. The tool allowed sales to show, in dollars and cents, what small improvements and changes could mean to their bottom line. Awesome for the client, kinda strenuous for the developer (moi) because numbers need to constantly change from a bare bones format that make AS3′s math functions happy, to a beautiful looking piece of art that might appear on a bank statement.

Adding in a dollar sign is easy, but how to add commas!? Being that AS3 offers virtually no support for number formatting I found myself cruising the private sector; reading one code monkeys opinion after another. While I found plenty of functions, it seemed like they all made assumptions on what the expected input would be. No numbers larger than 9999, no negative numbers, no decimal points, etc. I finally tossed on the ol’ headphones and cranked out my own addCommas function. It accepts a real number as an input and spits back the same number as a string with commas.

Have fun, make sure to have her home by ten:

function addCommas(number:Number):String {
var negNum:String = “”;
if(number<0){
negNum = “-”;
number = Math.abs(number);
}
var num:String = String(number);
var results:Array = num.split(/\./);
num=results[0];if (num.length>3) {
var mod:Number = num.length%3;
var output:String = num.substr(0, mod);
for (var i:Number = mod; i<num.length; i += 3) {
output += ((mod == 0 && i == 0) ? “” : “,”)+num.substr(i, 3);
}
if(results.length>1){
if(results[1].length == 1){
return negNum+output+”.”+results[1]+”0″;}else{
return negNum+output+”.”+results[1];
}
}else{
return negNum+output;
}
}

if(results.length>1){
if(results[1].length == 1){
return negNum+num+”.”+results[1]+”0″;

}else{
return negNum+num+”.”+results[1];
}
}else{
return negNum+num;
}}

Posted in: Development, FAQs / Tips & Tricks, Insights

13 Responses to “Formatting Numbers With Commas in AS3”

  1. comment number 1 by: Wyeth

    Hi there,
    Thanks for your script. It helped me. I had a problem though. When the number got up into higher digits, the commas were being placed in the wrong places. I tried a few things and then ended up replacing

    var mod:Number = num.length/3;

    with a switch statement:

    switch(num.length){
    case 4:
    mod = 1;
    break;

    case 5:
    mod = 2;
    break;

    case 6:
    mod = 3;
    break;

    case 7:
    mod = 1;
    break;

    case 8:
    mod = 2;
    break;

    case 9:
    mod = 3;
    break;
    }

    It worked perfectly after that.

    Thanks again,

    Best,

    -w

  2. comment number 2 by: Nixon

    hey there Wyeth,
    I’ve cranked some pretty big numbers through the function without a problem…

    I think the issue is that line you break out:
    var mod:Number = num.length/3;

    In actuality should read:
    var mod:Number = num.length%3;

    The percent sign being the modulus math operation. The modulus operator is doing the same thing as your switch statement in that, 4%3 = 1, 5%3=2 etc etc. Unfortunately the switch statement you’ve outlined won’t work on numbers with more than 9 digits.

    I would replace the switch with this:
    var mod:Number = num.length%3;

    I think the problem is from wordpress really butchering the code format… maybe I can attach a file for download…

  3. comment number 3 by: Jack

    Thanks for posting the code. Works great and saved me a ton of time.

    -Jack

  4. comment number 4 by: Scott

    I took a different approach — should work for any sized number. I didn’t need the negative detection, you should be able to add that to this easily if you need it.

    public function addCommas(number:Number):String
    {
    var numberString:String = String(number);
    var newString:String = “”;
    var col:int = 0;
    for (var index:int = numberString.length-1; index >= 0; index–)
    {
    col++;
    newString = numberString.substr(index, 1) + newString;
    if (col == 3 && index != 0)
    {
    newString = “,” + newString;
    col = 0;
    }

    }
    return newString;
    }

  5. comment number 5 by: nixon

    While your solution will work for any sized positive number it won’t handle numbers with a decimal point.

    For example 5.25 would be formatted 5,.25

    Our two functions aren’t behaving that much differently, personally, I find the flexibility to work with negative numbers and decimal points is worth the extra few lines of code because I can reuse the same function anytime I need formatted numbers and don’t have to revisit it when a special case comes along.

  6. comment number 6 by: Andrew

    As with jack – this came in very handy and works as expected; thanks for sharing it.

  7. comment number 7 by: Edenshaw

    First of all thanks for your function it helped me a lot.

    The only thing I found that is not working is with a number like this: “1593578642598796.32″ because the output will be “1,593,578,642,598,796.30″ as you can see, the last part change and it shouldn’t. The problem I found was the casting (sort of speak) of the changing between Number to String.

    When I debug your function, the line:

    var num:String = String(number);

    change the number “1593578642598796.32″ to “1593578642598796.3″ and assigns it to the variable “num” and from that point everything will go wrong.

    The only solution I found it was changing the type of parameter of the function, instead of “Number” change it to “String”:

    function addCommas( number:String ):String {

    and in the line:

    var num:String = String(number);

    change it to:

    var num:String = number;

    Perhaps if you believe that the problem is because is a decimal point number, if I try this number “1593578642598799996″ the output it will be “1,593,578,642,598,800,000″ I know that is some sort of approximation but if what you need is the exact number but with only commas, then this will be a problem. Again, the solution for this is changing the parameter of the function and the line of casting.

    P.S.: Sorry for my english and thanks again

  8. comment number 8 by: Edenshaw

    I change the parameter of the function to String because I took the number from a TextInput so is already a String.

  9. comment number 9 by: j_noob

    i just want to ask how can I call the function in an input box?sorry just a jscript newbie..you’re answers would be a great of help

  10. comment number 10 by: nixon

    Hey there,
    Looking into this I see it’s not so much the function having a problem, but it’s a limit of AS3 to deal with large values like this. AS3 doesn’t really have the capacity to use those values as a number data type. As you mentioned, changing this to a string will allow AS3 to properly format the number. I can’t even assign such values to a number variable and have it stored correctly, let alone run it through a function. I wasn’t aware of AS3′s limitation on large numbers prior to this, so thanks for bringing it to my attention. Supposedly there are classes in third party libraries like “BigInteger” to help facilitate some of this.

  11. comment number 11 by: nixon

    In general I stay away from formatting an input box. I think it is a bit jarring for a user to be typing and having things autoformat without their consent. I know plenty of people that can’t even handle t9 on their cell phones. Though, if you’re looking to do it you just need to add a key_up event listener onto the input box. better yet have the event listener on the next input box so that the number is only formatted once the user is no longer actively typing in the same box. Know what I mean?

  12. comment number 12 by: FlashMan

    @comment7:

    I think the reason why “0″ is added is because of this line:

    return negNum+output+”.”+results[1]+”0″;

    Why is the + “0″ needed?

    I removed it and now it works great, thank you!

  13. comment number 13 by: nixon

    That line could be causing problems if this function is converted to run with string variables. But as I mentioned previously the main problem for @comment7 was the limit in AS3 to handle large numbers without some kind of additional framework. Even trying to set a variable to one of those values and tracing it back gives the same results.

    Anywho, the line you’re referring to in your post:
    return negNum+output+”.”+results[1]+”0″;

    Is used to provide consistent formatting of numbers like 1.5 this line ensures that 1.50 is output instead. Often times this code is used for calculators and most sales/marketing people like to see numbers as they would appear on a cash register or receipt. Hence the additional 0.

Leave a Reply

Name

Mail (never published)

Website

Note: Because we value your thoughtful opinions, we encourage you to add a comment to this discussion. We reserve the right edit your comments for clarity or to keep out questionable matters, however, and we may even delete off-topic comments.



home     |     about     |     disclaimer     |     cgi interactive
© - CGI Interactive - 76 Otis Street - Westboro, MA 01581 - 508.898.2500