jQuery 每三位数加逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1990512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:32:28  来源:igfitidea点击:

Add comma to numbers every three digits

jquerynumber-formatting

提问by Steve

How can I format numbers using a comma separator every three digits using jQuery?

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

For example:

例如:

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

回答by Doug Neiner

@Paul Creasey had the simplest solution as the regex, but here it is as a simple jQuery plugin:

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

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

You could then use it like this:

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

$("span.numbers").digits();

回答by Abhijeet

You could use Number.toLocaleString():

你可以使用Number.toLocaleString()

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

回答by Paul Creasey

Something like this if you're into regex, not sure of the exact syntax for the replace tho!

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

MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",");

回答by Mark Byers

You could try NumberFormatter.

你可以试试NumberFormatter

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

It also supports different locales, including of course US.

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

Here's a very simplified example of how to use it:

这是一个非常简单的示例,说明如何使用它:

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

Output:

输出:

1,000
2,000,000

回答by Ray

This is not jQuery, but it works for me. Taken from this site.

这不是 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, '' + ',' + '');
    }
    return x1 + x2;
}

回答by Kamy D

2016 Answer:

2016 答案:

Javascript has this function, so no need for Jquery.

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

yournumber.toLocaleString("en");

回答by bamossza

Use function Number();

使用函数 Number();

$(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 />

回答by Nathan Long

A more thorough solution

更彻底的解决方案

The core of this is the replacecall. So far, I don't think any of the proposed solutions handle all of the following cases:

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

  • Integers: 1000 => '1,000'
  • Strings: '1000' => '1,000'
  • For strings:
    • Preserves zeros after decimal: 10000.00 => '10,000.00'
    • Discards leading zeros before decimal: '01000.00 => '1,000.00'
    • Does not add commas after decimal: '1000.00000' => '1,000.00000'
    • Preserves leading -or +: '-1000.0000' => '-1,000.000'
    • Returns, unmodified, strings containing non-digits: '1000k' => '1000k'
  • 整数: 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'

The following function does all of the above.

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

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

You could use it in a jQuery plugin like this:

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

$.fn.addCommas = function() {
  $(this).each(function(){
    $(this).text(addCommas($(this).text()));
  });
};

回答by bendewey

You can also look at the jquery FormatCurrencyplugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.

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

$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });

回答by Lam

Here is my javascript, tested on firefox and chrome only

这是我的 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>