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

"$ 2,500.00"

我该怎么做?


当前回答

我想为此做出贡献:

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>

其他回答

看看JavaScriptNumber对象,看看它是否可以帮助您。

toLocaleString()将使用位置特定的千位分隔符格式化数字。toFixed()将数字舍入到特定的小数位数。

要同时使用这些值,必须将其类型改回数字,因为它们都输出字符串。

例子:

Number((someNumber).toFixed(1)).toLocaleString()

EDIT

您可以直接使用toLocaleString,而不必重新转换为数字:

someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});

多个数字

如果需要经常以类似的方式格式化数字,可以创建一个特定的对象以供重用。德语(瑞士):

const money = new Intl.NumberFormat('de-CH',
  { style:'currency', currency: 'CHF' });
const percent = new Intl.NumberFormat('de-CH',
  { style:'percent', maximumFractionDigits: 1, signDisplay: "always"});

其可以用作:

money.format(1234.50); // output CHF 1'234.50
percent.format(0.083);  // output +8.3%

非常漂亮。

这是另一个尝试,只是为了好玩:

function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}

还有一些测试:

formatDollar(45664544.23423) // "$45,664,544.23"
formatDollar(45) // "$45.00"
formatDollar(123) // "$123.00"
formatDollar(7824) // "$7,824.00"
formatDollar(1) // "$1.00"
formatDollar(-1345) // "$-1,345.00
formatDollar(-3) // "$-3.00"

+1向Jonathan M提供原始方法。由于这是一个明确的货币格式化程序,我继续在输出中添加了货币符号(默认为“$”),并添加了一个默认逗号作为千位分隔符。如果您实际上不需要货币符号(或千位分隔符),只需使用“”(空字符串)作为它的参数。

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {
    // check the args and supply defaults:
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
    decSeparator = decSeparator == undefined ? "." : decSeparator;
    thouSeparator = thouSeparator == undefined ? "," : thouSeparator;
    currencySymbol = currencySymbol == undefined ? "$" : currencySymbol;

    var n = this,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;

    return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

这可能奏效:

function format_currency(v, number_of_decimals, decimal_separator, currency_sign){
  return (isNaN(v)? v : currency_sign + parseInt(v||0).toLocaleString() + decimal_separator + (v*1).toFixed(number_of_decimals).slice(-number_of_decimals));
}

没有循环,没有正则表达式,没有数组,没有奇异条件。

我想你想要:

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