Wednesday, March 28, 2012

Javascript Currcncy formatter

// Used to format the currency amount
function formatCurrencyAmount(amount) {

//replace non numeric value. can add more if any
amount= amount.toString().replace(/\$|\,/g, "");

if (isNaN(amount)) amount= "0";

sign = (amount== (amount= Math.abs(amount)));

amount= Math.floor(amount* 100 + 0.50000000001);

cents = amount% 100;

amount= Math.floor(amount/ 100).toString();

if (cents < 10) cents = "0" + cents;

for (var i = 0; i < Math.floor((amount.length - (1 + i)) / 3); i++)
amount= amount.substring(0, amount.length - (4 * i + 3)) + "," + amount.substring(amount.length - (4 * i + 3));

//Return it with the $ amount
return (((sign) ? "" : "-") + "$" + amount+ "." + cents);
}

Cheers,

No comments:

Post a Comment