【问题标题】:Add comma to numbers every three digits每三位数字添加逗号
【发布时间】:2010-12-31 17:20:19
【问题描述】:

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

例如:

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

【问题讨论】:

  • 我是 jQuery 新手,想要一个简单的函数/插件,如果数字长度超过三位数,只需在每三位数后添加逗号。仅正数,无分数,无小数,不涉及货币,标准美国格式 (1,111) 不是($1,111 或 $1,111.11)。如果可能的话,我宁愿使用 jQuery 而不仅仅是 javascript,并且最好将代码集设置为一个函数,以便可以非常轻松地应用它。我该怎么做呢?感谢大家的投入。再次感谢。
  • @unknown:你已经有很多答案了。查看您收到的答案并对其进行评估,以确定最适合您的答案。如果您需要对其中一个答案进行更多说明,请将其作为对该答案的评论发布。
  • 对不起,我的问题不够简洁,但请参阅使用 Paul Creasey 的代码的 Doug Neiner 插件格式以获得答案。

标签: jquery number-formatting


【解决方案1】:

@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();

【讨论】:

  • 完美运行!感谢 Paul Creasey 提供简单、优雅的代码,感谢 Doug Neiner 将其转换为插件格式。两者皆有功劳。
  • RC @Mark Byers 语法是正确的。 '999.9999'.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") 虽然返回 '999.9,999'。
  • 为输入字段做了一个小修改:$.fn.digits = function(){ return this.each(function(){ $(this).val( $(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); }) }
  • 我认为这将更适合 jQuery 名称空间实用程序样式函数,例如$.digits = function() { ... };.
  • 最快的方法是number.toLocaleString("en");
【解决方案2】:

你可以使用Number.toLocaleString():

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

【讨论】:

  • 我试过了,但不是在实时服务器上工作,而是在本地主机上工作..
  • @eladsilver w3schools.com/jsref/jsref_tolocalestring.asp 在所有浏览器中
  • 这对我来说最简单。我需要货币和逗号。我也可以设置属性:var n = 26787.89 var myObjCurrency = { style: "currency", currency: "USD", currencyDisplay : "symbol" } n.toLocaleString("en-US", myObjCurrency));
  • 如果你问我,这是最简单、最优雅的答案。
【解决方案3】:

如果您使用正则表达式,可能会遇到类似的情况,但不确定替换的确切语法!

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

【讨论】:

  • 语法是对的。 '999.9999'.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") 虽然返回 '999.9,999'。
  • @Unknown,我将其移至答案。使用示例在此页面的更下方。
【解决方案4】:

你可以试试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

【讨论】:

  • 我看了一眼这个插件,根据作者的描述,它是用来在表单输入字段中使用的。我怎样才能将它应用到 2984 所以它的格式为 2,984 没有小数。我试过 $('span.numbers').format({format:"#,###", locale:"us"});但什么也没发生。仍在检查插件,玩弄它。对不起,我是 jQuery 新手 :-)
  • +1 很高兴知道这个插件。我同意,对于增长和未来的国际化,这将是最好的途径。
  • 这里是它的 GitHub 存储库的链接。 github.com/hardhub/jquery-numberformatter
【解决方案5】:

2016 年答案:

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

yournumber.toLocaleString("en");

【讨论】:

  • 这适用于所有浏览器吗?它在 chrome 上运行良好。它可以在 IE9+ 和 opera、safari 上运行吗?
  • @zeppelin w3schools.com/jsref/jsref_tolocalestring.asp 支持所有浏览器
  • 只要确保您调用它的数字是数字类型(int、float 等)而不是字符串。
【解决方案6】:

这不是 jQuery,但它对我有用。取自this site

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

【讨论】:

  • 你们的“根”:)
  • "Rootsy" 可能是这样,但我认为其他花哨的方法在我的情况下不起作用,其中数据嵌入在 Canvas (Chart.JS) 中。但是添加该函数并在图表的 afterDraw() 事件中调用它非常有效: ctx.fillText(addCommas(dataset.data[i]),
  • 这不起作用,例如 3000000(7 位数)。仅适用于 6 位或更少的数字!
【解决方案7】:

使用函数 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 />

【讨论】:

  • 谢谢,我用了你的回答。值得注意的是,这只支持长度不超过 15 位的数字。
【解决方案8】:

更彻底的解决方案

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

  • 整数:1000 =&gt; '1,000'
  • 字符串:'1000' =&gt; '1,000'
  • 对于字符串:
    • 小数点后保留零:10000.00 =&gt; '10,000.00'
    • 丢弃小数点前的前导零:'01000.00 =&gt; '1,000.00'
    • 小数点后不加逗号:'1000.00000' =&gt; '1,000.00000'
    • 保留前导 -+: '-1000.0000' =&gt; '-1,000.000'
    • 返回未修改的包含非数字的字符串:'1000k' =&gt; '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()));
  });
};

【讨论】:

    【解决方案9】:

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

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

    【讨论】:

    • 这个问题促使我发布了这个插件的 v1.3,所以谢谢
    【解决方案10】:

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

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

    更新日期:2021 年 1 月 23 日

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

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

    【讨论】:

      【解决方案11】:

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

      【讨论】:

        【解决方案12】:
        function formatNumberCapture () {
        $('#input_id').on('keyup', function () {
            $(this).val(function(index, value) {
                return value
                    .replace(/\D/g, "")
                    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
                    ;
            });
        });
        

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

        【讨论】:

          【解决方案13】:

          使用此代码在 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;
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2015-05-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-15
            相关资源
            最近更新 更多