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



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