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:
  1. function formatCurrency(amount)
  2. {
  3.     var i = parseFloat(amount);
  4.     if(isNaN(i)) { i = 0.00; }
  5.     var minus = ;
  6.     if(i <0) { minus = ‘-’; }
  7.     i = Math.abs(i);
  8.     i = parseInt((i + .005) * 100);
  9.     i = i / 100;
  10.     s = new String(i);
  11.     if(s.indexOf(‘.’) <0) { s += ‘.00′; }
  12.     if(s.indexOf(‘.’) == (s.length - 2)) { s += ‘0′; }
  13.     s = minus + s;
  14.     return s;
  15. }

To use it just call it in the onBlur attribute of your input field.

HTML:
  1. <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.

Leave a Reply