Saturday, 6 August 2016

formatting - How can I format numbers as currency string in JavaScript?



I would like to format a price in JavaScript.
I'd like a function which takes a float as an argument and returns a string formatted like this:



"$ 2,500.00"



What's the best way to do this?


Answer



Ok, based on what you said, i'm using this:



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;


I'm open to improvement suggestions (i'd prefer not to include YUI just to do this :-) )
I already know I should be detecting the "." instead of just using it as the decimal separator...


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...