Number Format – Thousand Separator in AS3
Wednesday, August 12th, 2009Here’s a short number format function I wrote to easily paste in your code when needed. It’s really handy for currency formatting.
The first parameter (number:*) can be a Number, int, uint or a String class instance.
The last parameter (siStyle:Boolean) specifies whether to use the International System of Units or not. SI units have points between the thousands and a comma for the seperator (123.456.789,01). Putting siStyle as false reverses that behaviour (123,456,789.01).
It’s really ugly by design since I wanted it to be a single, tiny function. There’s loads of prettier/faster code samples out there.
function
numberFormat(number:*, maxDecimals:
int
= 2, forceDecimals:
Boolean
=
false
, siStyle:
Boolean
=
false
):
String
{
var
i:
int
= 0, inc:
Number
= Math.pow(10, maxDecimals), 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;
}