Return to Snippet

Revision: 22937
at April 4, 2011 23:56 by adrianparr


Updated Code
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
{
    var i:int = 0;
	var inc:Number = Math.pow(10, maxDecimals);
	var str:String = String(Math.round(inc * Number(number))/inc);
    	var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    	var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    	if (forceDecimals) {
		for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
	}
    	while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    	return str.substr(0, sep - i) + ret;
}

Revision: 22936
at April 4, 2011 23:56 by adrianparr


Updated Code
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
{
    	var i:int = 0;
	var inc:Number = Math.pow(10, maxDecimals);
	var str:String = String(Math.round(inc * Number(number))/inc);
    	var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    	var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    	if (forceDecimals) {
		for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
	}
    	while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    	return str.substr(0, sep - i) + ret;
}

Revision: 22935
at January 26, 2010 06:25 by adrianparr


Initial Code
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
{
    	var i:int = 0;
	var inc:Number = Math.pow(10, maxDecimals);
	var str:String = String(Math.round(inc * Number(number))/inc);
    	var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
    	var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
    	if (forceDecimals) {
		for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
	}
    	while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
    	return str.substr(0, sep - i) + ret;
}

Initial URL

                                

Initial Description
Format a number so it is more humanly readable. It allows for setting the number of decimal places (inc. adding 0000s to the end) and separating thousands with a comma.

Example usage:

trace(numberFormat(1234.695, 2, true, false)); 
// Output: 1,234.70

trace(numberFormat(16000000, 0, false, false)); 
// Output: 16,000,000

Initial Title
Format a Number to a String - With decimals and thousands separator

Initial Tags
number, format

Initial Language
ActionScript 3