Format a Number as Currency
By Stephen Bucaro
The easiest and most proper way to format a number as a currency value is to
use the Java Script Number object's toFixed method, as shown below.
var n = 314.7614;
var amt = n.toFixed(2);
The argument passed to the toFixed method sets the number of digits to
the right of the decimal point. The toFixed method rounds the number
up and adds zeros after the decimal point if needed to create the desired decimal length.
The toFixed method will only work in newer browsers like Internet
Explorer version 5.5 and later. If you can't be sure that all your users have
newer browsers than you can create your own function to format a number as a
currency, as shown below.
function toCurrency(num)
{
var n = Math.round(num * 100) / 100;
var m = n.toString();
var loc = m.indexOf(".");
if(loc < 0)
{
loc = m.length;
m += ".";
}
while(loc + 3 > m.length)
{
m += '0';
}
return m;
}
The first line in the toCurrency function moves first two digits of the
number from the right of decimal to left of the decimal point (or adds zeros if
required), rounds the number, then puts the decimal point back where it was.
The number is then converted to a string and the index of the decimal point in
the string is acquired. The if structure checks if there is no decimal
point in the number. if not, it puts one at the end of the number.
The while structure makes sure there are two digits to right of the
decimal point. If not. it adds zeros as required. The function then returns the
currency formatted number.
The line below shows how you could pass a number to the toCurrency function.
var k = 120.6234;
var amt = toCurrency(k);
Or just pass the numeric value as shown below.
var amt = toCurrency(120.6234);
