Formating Numbers with Commas

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
*/

The function formatNum() returns a string given a number argument … it adds commas where appropriate and takes into account decimal values. This is useful anywhere you need to display numbers over 1,000, in a game, in a calculator app etc…

Leave a Reply

Your email address will not be published. Required fields are marked *