How can I format numbers as money in JavaScript?

Posted by Daniel Magliola on Stack Overflow See other posts from Stack Overflow or by Daniel Magliola
Published on 2008-09-29T15:00:28Z Indexed on 2010/05/27 9:41 UTC
Read the original article Hit count: 156

Filed under:
|

I would like to format a price in JavaScript.
Basically, I have a float variable, and I'd like to have a function that will receive that variable, and output:

"$ 2,500.00"

What's the best way to do this?

EDIT: OK, since I haven't gotten any answers better than the code I implemented, plus my own answer has been voted down and I can't put my own answer as the right one... Here it is...

var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);

var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);

return '£ ' + intPart + DecimalSeparator + decPart;

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about formatting