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

"$ 2,500.00"

我该怎么做?


当前回答

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 });
}

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

其他回答

请尝试以下代码

"250000".replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');

答案:250000

我选择了一些最好的答案,组合并制作了一个通过ESLint的ECMAScript 2015(ES6)函数。

export const formatMoney = (
  amount,
  decimalCount = 2,
  decimal = '.',
  thousands = ',',
  currencySymbol = '$',
) => {
  if (typeof Intl === 'object') {
    return new Intl.NumberFormat('en-AU', {
      style: 'currency',
      currency: 'AUD',
    }).format(amount);
  }
  // Fallback if Intl is not present.
  try {
    const negativeSign = amount < 0 ? '-' : '';
    const amountNumber = Math.abs(Number(amount) || 0).toFixed(decimalCount);
    const i = parseInt(amountNumber, 10).toString();
    const j = i.length > 3 ? i.length % 3 : 0;
    return (
      currencySymbol +
      negativeSign +
      (j ? i.substr(0, j) + thousands : '') +
      i.substr(j).replace(/(\d{3})(?=\d)/g, `$1${thousands}`) +
      (decimalCount
        ? decimal +
          Math.abs(amountNumber - i)
            .toFixed(decimalCount)
            .slice(2)
        : '')
    );
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(e);
  }
  return amount;
};

我想为此做出贡献:

function toMoney(amount) {
    neg = amount.charAt(0);
    amount = amount.replace(/\D/g, '');
    amount = amount.replace(/\./g, '');
    amount = amount.replace(/\-/g, '');

    var numAmount = new Number(amount);
    amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {
        return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;
    });

    if(neg == '-')
        return neg + amount;
    else
        return amount;
}

这允许您在一个文本框中转换数字,在该文本框中您只需要输入数字(考虑这种情况)。

这将清理一个文本框,其中只有数字,即使你粘贴了一个包含数字、字母或任何字符的字符串

<html>
<head>
    <script language=="Javascript">
        function isNumber(evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            if (key.length == 0)
                return;
            var regex = /^[0-9\-\b]+$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault)
                    theEvent.preventDefault();
            }
        }

        function toMoney(amount) {
            neg = amount.charAt(0);
            amount = amount.replace(/\D/g, '');
            amount = amount.replace(/\./g, '');
            amount = amount.replace(/\-/g, '');

            var numAmount = new Number(amount);
            amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {
                return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;
            });

            if(neg == '-')
                return neg + amount;
            else
                return amount;
        }

        function clearText(inTxt, newTxt, outTxt) {
            inTxt = inTxt.trim();
            newTxt = newTxt.trim();
            if(inTxt == '' || inTxt == newTxt)
                return outTxt;

            return inTxt;
        }

        function fillText(inTxt, outTxt) {
            inTxt = inTxt.trim();
            if(inTxt != '')
                outTxt = inTxt;

            return outTxt;
        }
    </script>
</head>

<body>
    $ <input name=reca2 id=reca2 type=text value="0" onFocus="this.value = clearText(this.value, '0', '');" onblur="this.value = fillText(this.value, '0'); this.value = toMoney(this.value);" onKeyPress="isNumber(event);" style="width:80px;" />
</body>

</html>

我们也可以使用numeraljs

数字的格式可以像货币、百分比、时间,甚至是带有小数位数、千位和缩写的普通数字。您可以始终创建自定义格式。

var string = numeral(1000).format('0,0');
// '1,000'

处理货币输出(包括负数)的函数。样本输出:$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();
}