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.





Just a little simpler without the array:
public function prettifyNumber(value:Number):String
{
var txt:String = "";
var num:String = value.toString();
var dec:Array = num.split(".");
num = dec.shift();
var j:int = 0;
for (var i:int = num.length % 3 || 3; i < num.length; i += 3) {
txt += num.substring(j, i) + ",";
j = i;
}
txt += num.substring(j, i);
if (dec.length) {
txt += "." + dec;
}
return txt;
}
@tyler, perfect man. Thanks.
why not just use the Formatter class?
@Zee: Right, I forgot about that. I’ve only used the Formatter class for things like email addresses and such. I find it a pain in the ass to use those classes. Mainly because I use them so infrequently. Perhaps I should practice.