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

"$ 2,500.00"

我该怎么做?


当前回答

我想你想要:

f.nettotal.value = "$" + showValue.toFixed(2);

其他回答

tggagne是正确的。由于浮动舍入,我下面的解决方案不好。toLocaleString函数缺少一些浏览器支持。出于存档目的,我将留下以下评论,说明不该做什么。:)

Date.product.toLocaleString()

(旧解决方案)使用Patrick Desjardins的解决方案。

这是一个简洁的解决方案,它使用toLocaleString(),自JavaScript 1.0版以来一直支持该解决方案。此示例将货币指定为美元,但可以使用“GBP”而不是“USD”转换为英镑。

var formatMoney = function (value) {
    // Convert the value to a floating point number in case it arrives as a string.
    var numeric = parseFloat(value);
    // Specify the local currency.
    return numeric.toLocaleString('USD', { style: 'currency', currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

有关更多详细信息,请参阅国际化和本地化,货币。

javascript数字格式化程序(以前在Google Code)

短、快、灵活但独立。接受标准数字格式,如#、##0.00或带否定的-000.####。接受任何国家/地区格式,如###0,00,#,###.##,#‘###.##或任何类型的非编号符号。接受任意数字分组。#、##、#0.000或#、####0.##均有效。接受任何冗余/万无一失的格式。##、###、##。#或0#、#00####0#都正常。自动数字舍入。简单的界面,只需提供如下掩码和值:格式(“0.0000”,3.141592)。在掩码中包含前缀和后缀

(摘自自述)

Patrick热门答案的CoffeeScript:

Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->
  n = this
  c = decimalPlaces
  d = decimalChar
  t = thousandsChar
  c = (if isNaN(c = Math.abs(c)) then 2 else c)
  d = (if d is undefined then "." else d)
  t = (if t is undefined then "," else t)
  s = (if n < 0 then "-" else "")
  i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + ""
  j = (if (j = i.length) > 3 then j % 3 else 0)
  s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "")

JavaScript中有一个内置函数toFixed:

var num = new Number(349);
document.write("$" + num.toFixed(2));

一种仅满足原始要求的极简方法:

function formatMoney(n) {
    return "$ " + (Math.round(n * 100) / 100).toLocaleString();
}

@丹尼尔·马格廖拉:你说得对。以上是一个仓促而不完整的实施。以下是正确的实施方式:

function formatMoney(n) {
    return "$ " + n.toLocaleString().split(".")[0] + "."
        + n.toFixed(2).split(".")[1];
}