javascriptformattingcurrency

How to format numbers as currency strings


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"

How can I do this?


Solution

  • 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...