While working on Slikcalc, I was trying to find the easiest way to format a number for currency. I had found some implementations that were pretty complex, using regex and absolute values, and thought there had to be a simpler way. This is what I came up with and so it works great in all the browsers I’ve tested (IE 6/7, Firefox 2 (windows & mac), Opera 9 (windows and mac).
function formatCurrency(num) {
num = isNaN(num) || num === '' || num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
Just thought I’d share for anyone working with something similar.
30 Comments
Thanks for this option and can you please provide a working sample. Specifically, if i already have code in place, how can i run this function against a variable and/or form field value? I would introduce my code, but I don’t want you to fall out of your chair laughing or anything!!
Just learning.
Thanks and sorry if its a ridiculous question!
I would imagine you want this code to be used in conjunction with an input field, perhaps onblur you want to format the currency for that field. You could set that up a number of ways, preferably using some type of javascript library to add the event listener. For the sake of simplicity, I’ll assume no library is being used, and you just want to add it inline. You would need to have the formatCurrency function defined somewhere, such as below (I’ve wrapped it into a util object for an example of how you would avoid global functions):
You could then add the onblur listener inline in your html. I would suggest using a library like YUI or jQuery to handle adding your listeners, but without getting into that, here is what you would have inline for your input you wanted to have formatted on blur of the field:
This code warrants a disclaimer, as I haven’t tested it, but it should give you a good start. Hope that helps!
Where IS the comma?
$ 1,000.00
The COMMA, also MINUS and DOLLAR sign, and a few more details….
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;
for (var i = 0; i < Math.floor((num.length – (1 + i)) / 3); i++)
num = num.substring(0, num.length – (4 * i + 3)) + ‘,’ + num.substring(num.length – (4 * i + 3));
return (((sign) ? ” : ‘-’) + ‘$’ + num + ‘.’ + cents);
}
I was able to use your JS currency function in a project at work. Your work is interesting. Thanks for sharing
Hope I may be able to reciprocate somehow, someday. Nice to have the option to use tags in the comments section.
Thanks Mate. You are genius
I am wondering if anyone can tell me where the function submitted by Alex G aboce would be included?
Nice. Thanks
Thanks, it is very good article
thanks it was very helpful in my case for a big nice project =)
Thanks, worked like a charm. Simple, and elegant.
Thanks. So simple, but I didn’t want to write it!
Alex G. Function works like a charm!
Note: if you copy from here and paste it in your code edit, it will not work correctly becase the double and single-quotation characters screwed up. Just replace them, then it will works fine.
Thank you,
Can anyone give me the correct one without the jumbled quotation?
thx man was just looking for something like this nice function
I added this as “a gist for easier cutting/pasting.
sorry, bad comment. here ya go, http://braxtoninaustin.com/2011/02/converting-a-number-to-currency-with-javascript/
For those of you that use jQuery there is an elegant solution out there via a jQuery plug-in. This is a link to the usage page so you can see some examples of how it’s used.
http://code.google.com/p/jquery-formatcurrency/wiki/Usage
Hope this helps!
A Google code project, although a little overkill, but still pretty short.
http://code.google.com/p/javascript-number-formatter/
* Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
* Accept standard number formatting like #,##0.00 or with negation -000.####.
* Accept any country format like # ##0,00, #,###.##, #’###.## or any type of non-numbering symbol.
* Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
* Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
* Auto number rounding.
* Simple interface, just supply mask & value like this: format( “0.0000″, 3.141592).
thanks for the code! and if you don’t want to show .00 if it’s a round dollar:
Thanks this was very helpful. Thanks to Alex G for adding additional elements!
Thanks Alex G, this has worked great for me too, I’m using this function with on blur, I have removed the $ sign to apply to my own currency, however when the form submits, I need the number submitted to be a round number i.e 1,200.89 to be 120089. Can someone help me on how I can make this function happen on two fields when the form is submitted. I hope I am making sense, am very very new to javascript.
I have the following function happening onblur, however I would like this to happen onsubmit on two fields only out of the about 10 input fields I have on the form, Can someone help me please, very clueless here, and I can see my problem is so dumb as I cant seem to find anything on forums on the net… please help
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;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+''+
num.substring(num.length-(4*i+3));
return (((sign)?'':'') + '' + num + '' + cents);
}
Perfect. Thank you!
Great little formatting function, works well. Thanks.
total = total.toFixed(2);
var priceArray = /(\d+)\.(\d+)/.exec(total);
var totalDollars = priceArray[1];
var totalCents = priceArray[2];
// add commas
var formattedDollars = ”;
totalDollars = totalDollars.toString();
for(var i=0; i 0) {
formattedDollars += ‘,’;
}
formattedDollars += totalDollars.substring(i, i+1);
}
that last comment didn’t take my if statement. oh well.
Thanks, worked great/right the first time!
Thanks for the function. Clean, concise, handles plenty of edge cases. Perfect!
<3
2 Trackbacks
[...] new version of Slikcalc (1.0) was released. This release simplified some code, mainly the slikcalc.formatCurrency() method. There was also a bug where a calculator could be initialized more than once depending on timing [...]
[...] 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 [...]