175

如何使用 jQuery 每三位使用逗号分隔符格式化数字?

例如:

╔═══════════╦═════════════╗
║   Input   ║   Output    ║
╠═══════════╬═════════════╣
║       298 ║         298 ║
║      2984 ║       2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝
4

13 回答 13

261

@Paul Creasey 有最简单的正则表达式解决方案,但这里是一个简单的 jQuery 插件:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

然后你可以像这样使用它:

$("span.numbers").digits();
于 2010-01-02T04:18:30.093 回答
118

你可以使用Number.toLocaleString()

var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534

于 2016-01-08T07:16:24.250 回答
81

如果您使用正则表达式,则类似这样的东西,不确定替换的确切语法!

MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
于 2010-01-02T03:50:52.677 回答
27

你可以试试NumberFormatter

$(this).format({format:"#,###.00", locale:"us"});

它还支持不同的语言环境,当然包括美国。

这是如何使用它的一个非常简化的示例:

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="jquery.numberformatter.js"></script>
        <script>
        $(document).ready(function() {
            $(".numbers").each(function() {
                $(this).format({format:"#,###", locale:"us"});
            });
        });
        </script>
    </head>
    <body>
        <div class="numbers">1000</div>
        <div class="numbers">2000000</div>
    </body>
</html>

输出:

1,000
2,000,000
于 2010-01-02T03:33:19.030 回答
26

2016 年答案:

Javascript有这个功能,所以不需要Jquery。

yournumber.toLocaleString("en");
于 2016-02-17T00:58:28.320 回答
24

这不是 jQuery,但它对我有用。取自本站

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
于 2010-01-02T03:45:55.493 回答
24

使用函数编号();

$(function() {

  var price1 = 1000;
  var price2 = 500000;
  var price3 = 15245000;

  $("span#s1").html(Number(price1).toLocaleString('en'));
  $("span#s2").html(Number(price2).toLocaleString('en'));
  $("span#s3").html(Number(price3).toLocaleString('en'));

  console.log(Number(price).toLocaleString('en'));

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<span id="s1"></span><br />
<span id="s2"></span><br />
<span id="s3"></span><br />

于 2015-07-08T07:28:59.640 回答
17

更彻底的解决方案

这个的核心是replace调用。到目前为止,我认为任何提议的解决方案都不能处理以下所有情况:

  • 整数:1000 => '1,000'
  • 字符串:'1000' => '1,000'
  • 对于字符串:
    • 在小数点后保留零:10000.00 => '10,000.00'
    • 丢弃小数点前的前导零:'01000.00 => '1,000.00'
    • 小数点后不加逗号:'1000.00000' => '1,000.00000'
    • 保留前导-+'-1000.0000' => '-1,000.000'
    • 返回未修改的包含非数字的字符串:'1000k' => '1000k'

以下函数完成上述所有操作。

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

您可以在这样的 jQuery 插件中使用它:

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};
于 2012-06-22T10:56:39.720 回答
9

您还可以查看 jquery FormatCurrency插件(我是该插件的作者);它也支持多种语言环境,但可能会产生您不需要的货币支持的开销。

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
于 2010-01-02T03:45:07.320 回答
7

非常简单的方法是使用toLocaleString()函数

tot = Rs.1402598 //Result : Rs.1402598

tot.toLocaleString() //Result : Rs.1,402,598

更新日期:23/01/2021

变量应该是数字格式。例子 :

Number(tot).toLocaleString() //Result : Rs.1,402,598
于 2019-08-27T15:45:31.327 回答
5

这是我的 javascript,仅在 Firefox 和 chrome 上测试

<html>
<header>
<script>
    function addCommas(str){
        return str.replace(/^0+/, '').replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function test(){
        var val = document.getElementById('test').value;
        document.getElementById('test').value = addCommas(val);
    }
</script>
</header>
<body>
<input id="test" onkeyup="test();">
</body>
</html>
于 2019-01-03T06:59:46.663 回答
2
function formatNumberCapture () {
$('#input_id').on('keyup', function () {
    $(this).val(function(index, value) {
        return value
            .replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
            ;
    });
});

你可以试试这个,它对我有用

于 2020-07-17T14:02:08.357 回答
0

使用此代码仅添加数字并在 jquery 的输入文本中的三位数后添加逗号:

$(".allow-numeric-addcomma").on("keypress  blur", function (e) {
   return false; 
});

$(".allow-numeric-addcomma").on("keyup", function (e) {

    var charCode = (e.which) ? e.which : e.keyCode
if (String.fromCharCode(charCode).match(/[^0-9]/g))
    return false;

value = $(this).val().replace(/,/g, '') + e.key;
var nStr = value + '';
nStr = nStr.replace(/\,/g, "");
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
}

$(this).val(x1 + x2);
return false;
});
于 2021-12-26T07:09:33.563 回答