function formatCurrency(num)
{
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10) cents = "0" + cents;
return (((sign)?'':'-') + num + '.' + cents);
}
Programming tips, tricks and advice from Jonathan Leger, a seasoned professional programmer/analyst.
ASP.NET, VB.NET, Visual Basic, MS Access, MS SQL Server, PHP, MySQL, JavaScript and more!
Monday, July 19, 2004
JavaScript Function to Format Currency (Money)
I am going to be posting a series of useful JavaScript functions for form validation and input formatting. This is the first in that series: a function which formats a number as currency.