Add commas to a number for readability
Do you need to display a large number and want to add commas to it for readability. The following code should work. Actually, it works for numbers that aren’t too big. Not sure when it starts to break down but passing Number.MAX_VALUE definitely doesn’t work. :) But, for regular numbers smaller than the national debt you’re probably in luck.
public static function commatizeNumber( n:Number ):String {
var a:Array = new Array();
var commatized:String = '';
var decimal:String = '';
if( int( n ) != n ) {
// if the number isn't an integer then get everything after the decimal
decimal = '.' + n.toString().split( '.' )[1];
n = int( n ); // make n an integer
}
var numString:String = String( n );
var place:int = numString.length; // start at the end
while( place > 0 ) {
var s:String;
// stop the while-loop
if( place - 3 < 0 ) {
place = 0;
s = numString.substr( 0, numString.length % 3 );
} else {
place -= 3;
s = numString.substr( place, 3 );
}
a.push( s );
}
var len:int = a.length
for( var i:int = len - 1; i >= 0; i-- ) {
// prevents the addition of a comma at the end of the String.
commatized += ( i != 0 ) ? a[i] + ',' : a[i];
}
commatized += decimal;
return commatized;
}
This code seems a bit inelegant to me. Maybe it’s because I wrote it this morning before having coffee. :) Let me know if you see a way to make it better.
If something here has proved valuable to you then feel free to drop a couple of bucks in the tip-jar.






