Friday, November 05, 2010

A poor man's Currency Formatter

*Title stolen from Arthur Debert Tweener tips.

While the Adobe flash.globalization package is still in beta, which includes a CurrencyFormatter class, we need to find a quick way to display an amount formatted as currency, with thousand separator and decimal mark.
In this case, we are targeting USA and UK so the thousand separator is a comma and the decimal mark is a point.
Right, so this is some simple logic used:
  • multiply the number by 100 to get the decimals
  • check if new number is zero or less than 100 (if less than 100 then is a decimal)
  • otherwise get the decimals and keep them aside
  • divide the rest of the number into groups of three and push them into an array
  • reverse the array and add the decimals
  • voila! you got the number formatted as currency!
So, yeah, the commas in that separate elements in the array work now as thousand separators :)
And here is the code:
private function formatCurrency(amount : Number) : String
{
var newAmount : String = String(Math.round(100 * amount));

if (newAmount.length == 1) newAmount = '0';

else if (newAmount.length == 2) newAmount = '0.' + newAmount;

else
{
var decimals : String = '.' + newAmount.slice(-2);
newAmount = newAmount.substring(0, newAmount.length - 2);

var amountGroup : Array = new Array();
while (newAmount.length > 3)
{
amountGroup.push(newAmount.slice(-3));
newAmount = newAmount.substring(0, newAmount.length - 3);
}
amountGroup.push(newAmount);
amountGroup.reverse();
newAmount = (Number(decimals) > 0) ? (amountGroup.join() + decimals) : amountGroup.join();
}
return newAmount;
}

Oh well, it does the job and as the CurrencyFormatter from Adobe is not implemented YET in pure AS3 (Flex Builder 4*), that code is useful :)

Salut!

*The CurrencyFormatter supported in Flex SDK 4.1 works with MXML only.

No comments: