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

"$ 2,500.00"

我该怎么做?


当前回答

已经有好的答案了。这里有一个简单的乐趣尝试:

function currencyFormat(no) {
  var ar = (+no).toFixed(2).split('.');
  return [
      numberFormat(ar[0] | 0),
      '.',
      ar[1]
  ].join('');
}


function numberFormat(no) {
  var str = no + '';
  var ar = [];
  var i  = str.length -1;

  while(i >= 0) {
    ar.push((str[i-2] || '') + (str[i-1] || '') + (str[i] || ''));
    i = i-3;
  }
  return ar.reverse().join(',');
}

然后运行一些示例:

console.log(
  currencyFormat(1),
  currencyFormat(1200),
  currencyFormat(123),
  currencyFormat(9870000),
  currencyFormat(12345),
  currencyFormat(123456.232)
)

其他回答

我想为此做出贡献:

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>

主要部分是插入千个分隔符,可以这样做:

<script type="text/javascript">
  function ins1000Sep(val) {
    val = val.split(".");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].replace(/(\d{3})/g, "$1,");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];
    return val.join(".");
  }

  function rem1000Sep(val) {
    return val.replace(/,/g, "");
  }

  function formatNum(val) {
    val = Math.round(val*100)/100;
    val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";
    var dec = val.indexOf(".");
    return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);
  }
</script>

<button onclick="alert(ins1000Sep(formatNum(12313231)));">

使用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;
}

YUI代码库使用以下格式:

format: function(nData, oConfig) {
    oConfig = oConfig || {};

    if(!YAHOO.lang.isNumber(nData)) {
        nData *= 1;
    }

    if(YAHOO.lang.isNumber(nData)) {
        var sOutput = nData + "";
        var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";
        var nDotIndex;

        // Manage decimals
        if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) {
            // Round to the correct decimal place
            var nDecimalPlaces = oConfig.decimalPlaces;
            var nDecimal = Math.pow(10, nDecimalPlaces);
            sOutput = Math.round(nData*nDecimal)/nDecimal + "";
            nDotIndex = sOutput.lastIndexOf(".");

            if(nDecimalPlaces > 0) {
                // Add the decimal separator
                if(nDotIndex < 0) {
                    sOutput += sDecimalSeparator;
                    nDotIndex = sOutput.length-1;
                }
                // Replace the "."
                else if(sDecimalSeparator !== "."){
                    sOutput = sOutput.replace(".",sDecimalSeparator);
                }
                // Add missing zeros
                while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
                    sOutput += "0";
                }
            }
        }

        // Add the thousands separator
        if(oConfig.thousandsSeparator) {
            var sThousandsSeparator = oConfig.thousandsSeparator;
            nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
            nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
            var sNewOutput = sOutput.substring(nDotIndex);
            var nCount = -1;
            for (var i=nDotIndex; i>0; i--) {
                nCount++;
                if ((nCount%3 === 0) && (i !== nDotIndex)) {
                    sNewOutput = sThousandsSeparator + sNewOutput;
                }
                sNewOutput = sOutput.charAt(i-1) + sNewOutput;
            }
            sOutput = sNewOutput;
        }

        // Prepend prefix
        sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;

        // Append suffix
        sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;

        return sOutput;
    }
    // Still not a number. Just return it unaltered
    else {
        return nData;
    }
}

它需要编辑,因为YUI库是可配置的,比如用“.”替换oConfig.decimalSeparator。

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 "")