我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:

"$ 2,500.00"

我该怎么做?


当前回答

如果金额是一个数字,比如-123,那么

amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });

将生成字符串“-123.00”。

这是一个完整的工作示例。

其他回答

Patrick Desjardins(前Daok)的例子对我很有用。如果有人感兴趣,我将其移植到CoffeeScript。

Number.prototype.toMoney = (decimals = 2, decimal_separator = ".", thousands_separator = ",") ->
    n = this
    c = if isNaN(decimals) then 2 else Math.abs decimals
    sign = if n < 0 then "-" else ""
    i = parseInt(n = Math.abs(n).toFixed(c)) + ''
    j = if (j = i.length) > 3 then j % 3 else 0
    x = if j then i.substr(0, j) + thousands_separator else ''
    y = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_separator)
    z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else ''
    sign + x + y + z

使用regexp的更快方法:

Number.prototype.toMonetaryString = function() {
  var n = this.toFixed(2), m;
  //var = this.toFixed(2).replace(/\./, ','); For comma separator
  // with a space for thousands separator
  while ((m = n.replace(/(\d)(\d\d\d)\b/g, '$1 $2')) != n)
      n = m;
  return m;
}

String.prototype.fromMonetaryToNumber = function(s) {
  return this.replace(/[^\d-]+/g, '')/100;
}

我使用库Globalize(来自Microsoft):

这是一个很好的项目,可以本地化数字、货币和日期,并根据用户的语言环境以正确的方式自动格式化它们。。。尽管它应该是一个jQuery扩展,但它目前是一个100%独立的库。我建议大家都试试看!:)

处理货币输出(包括负数)的函数。样本输出:$5.23-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

JavaScript中没有“formatNumber”的等价物。你可以自己写,也可以找一个已经这样做的库。