How can I format numbers as dollars currency strin

2018-12-30 23:37发布

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?

30条回答
还给你的自由
2楼-- · 2018-12-30 23:50

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

查看更多
大哥的爱人
3楼-- · 2018-12-30 23:51

I think what you want is f.nettotal.value = "$" + showValue.toFixed(2);

查看更多
春风洒进眼中
4楼-- · 2018-12-30 23:51
function CurrencyFormatted(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

From WillMaster.

查看更多
爱死公子算了
5楼-- · 2018-12-30 23:52

Take a look at the JavaScript Number object and see if it can help you.

  • toLocaleString() will format a number using location specific thousands separator.
  • toFixed() will round the number to a specific number of decimal places.

To use these at the same time the value must have its type changed back to a number because they both output a string.

Example:

Number(someNumber.toFixed(1)).toLocaleString()
查看更多
十年一品温如言
6楼-- · 2018-12-30 23:54

Patrick Desjardins' answer looks good, but I prefer my javascript simple. Here's a function I just wrote to take a number in and return it in currency format (minus the dollar sign)

// Format numbers to two decimals with commas
function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    var chars = p[0].split("").reverse();
    var newstr = '';
    var count = 0;
    for (x in chars) {
        count++;
        if(count%3 == 1 && count != 1) {
            newstr = chars[x] + ',' + newstr;
        } else {
            newstr = chars[x] + newstr;
        }
    }
    return newstr + "." + p[1];
}
查看更多
呛了眼睛熬了心
7楼-- · 2018-12-30 23:54

I suggest the NumberFormat class from Google Visualization API.

You can do something like this:

var formatter = new google.visualization.NumberFormat({
    prefix: '$',
    pattern: '#,###,###.##'
});

formatter.formatValue(1000000); // $ 1,000,000

I hope it helps.

查看更多
登录 后发表回答