formatCurrency Javascript Function
I use this javascript function all the time on web projects. Unfortunately I can’t remember where I got it from. Very handy though. It will take a number and format it as a currency so 123 becomes 123.00 or 123.456 becomes 123.46.
JavaScript:
-
function formatCurrency(amount)
-
{
-
var i = parseFloat(amount);
-
if(isNaN(i)) { i = 0.00; }
-
var minus = ”;
-
if(i <0) { minus = ‘-’; }
-
i = Math.abs(i);
-
i = parseInt((i + .005) * 100);
-
i = i / 100;
-
s = new String(i);
-
if(s.indexOf(‘.’) <0) { s += ‘.00′; }
-
if(s.indexOf(‘.’) == (s.length - 2)) { s += ‘0′; }
-
s = minus + s;
-
return s;
-
}
To use it just call it in the onBlur attribute of your input field.
HTML:
-
<input type=“text” name=“input_name” onBlur=“this.value=formatCurrency(this.value);”>
Question, Comments...
Do you have more questions. Please either leave a comment below or join us in our new forum.

