Converting a number to currency with Javascript

I recently needed a way to convert a number to currency format using Javascript.  I found the best solution in Alex G’s comment on Brad Harris’s post.  But as usual, there were issues when cutting/pasting from the web so I just wanted to post here as a Gist so it might help someone else and also so that someone can improve it if they want.

7 thoughts on “Converting a number to currency with Javascript”

  1. How do I run this function onsubmit on a form with other fields containing numbers, I would like this to happen on 2 fields onl out of about 10 fields with some containing numbers, I have it working with onblur for the fields, but ideally I need it on submit, please help…

  2. thank you for your response Braxton, I’m a little jquery and java challenged, I have achieved the little I have through some erratic googling. I’m not sure how I would implement your advice, would I copy this into the java script tags, naming the form & fields correctly of course, or am I totally off track? this is what I currently have running onblur, with the commas etc removed, as the submitted number cannot have commas and dots…. I have another function that formats into currency on keypress, and then blurs out as shown below. Now I need the 2 fields as explained to only do this onsubmit as users might be freaked out when they type in the amount with commas, and they dissapear ob blur. Even though I’ve temporarily put a notice that the value will be foramatted to cents.

    function formatCurrency(num) {
    num = num.toString().replace(/$|,/g,”);
    num = “0”;
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+''+
    return (((sign)?'':'') + '' + num + '' + cents);

  3. wow Braxton, I think I’m more confused, I understand the logic behind your suggestion, but I’m completely stumped on implementation, if you have a look at this link, you’ll see what I’m working on, I’ve removed the onblur on the first amount field, but you’ll see on the second amount field, I need that onblur occuring there to only happen onsubmit on both fields. I was hoping it’s achievable by a few additions to the javascript I posted earlier, i.e that it only happens onsubmit on those 2 fields, then the client always sees what they typed as the first is field currently doing, but once they submit it does once currently happening onblur. no simpler way than the jquery route you’ve advised?

Comments are closed.