Javascript 在 jQuery 中为数字添加逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3883342/
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-23 06:29:17  来源:igfitidea点击:

add commas to a number in jQuery

javascriptjqueryformattingnumbers

提问by Jamie Taylor

I have these numbers

我有这些数字

10999and 8094and 456

109998094456

And all i want to do is add a comma in the right place if it needs it so it looks like this

我想要做的就是在需要时在正确的位置添加一个逗号,因此它看起来像这样

10,999and 8,094and 456

10,9998,094456

These are all within a p tag like this <p class="points">10999</p>etc.

这些都在像这样的 ap 标签中<p class="points">10999</p>

Can it be done?

可以做到吗?

I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/but can't seem to get it to work

我在其他帖子http://jsfiddle.net/pdWTU/1/的帮助下在这里尝试过,但似乎无法让它工作

Thanks

谢谢

Jamie

杰米

UPDATE

更新

Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/

有点混乱并设法在这里弄清楚http://jsfiddle.net/W5jwY/1/

Going to look at the new Globalization plugin for a better way of doing it

将查看新的全球化插件以获得更好的方法

Thanks

谢谢

Jamie

杰米

回答by Timothy Perez

Works on all browsers, this is all you need.

适用于所有浏览器,这就是您所需要的。

  function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
      val = val.toString().replace(/(\d+)(\d{3})/, ''+','+'');
    }
    return val;
  }

Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:

由于正则表达式,因此将其写得紧凑且切中要害。这是直接的 JS,但您可以像这样在 jQuery 中使用它:

$('#elementID').html(commaSeparateNumber(1234567890));

or

或者

$('#inputID').val(commaSeparateNumber(1234567890));

回答by sonnenhaft

Number(10000).toLocaleString('en');  // "10,000"

回答by Tosin Onikute

Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.

Timothy Pirez 的回答非常正确,但是如果您需要在用户在文本字段中输入时立即用逗号替换数字,您可能想要使用 Keyup 功能。

      $('#textfield').live('keyup', function (event) {
        var value=$('#textfield').val();

      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var newvalue=value.replace(/,/g, '');   
      var valuewithcomma=Number(newvalue).toLocaleString('en');   
      $('#textfield').val(valuewithcomma); 

      });

    <form><input type="text" id="textfield" ></form>

回答by adamwdraper

Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.

看看Numeral.js。它可以格式化数字、货币、百分比并支持本地化。

回答by Sumith Harshan

    function delimitNumbers(str) {
      return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
        return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, ",") : b) + c;
      });
    }

    alert(delimitNumbers(1234567890));

回答by Jakub Konecki

Take a look at recently released Globalization pluginto jQuery by Microsoft

看看微软最近发布的jQuery全球化插件

回答by Deniz Dogan

I'm guessing that you're doing some sort of localization, so have a look at this script.

我猜你正在做某种本地化,所以看看这个脚本

回答by abhiklpm

another approach:

另一种方法:

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;
}
var a  = addCommas(10000.00);
alert(a);

Another amazing plugin: http://www.teamdf.com/web/jquery-number-format/178/

另一个惊人的插件:http: //www.teamdf.com/web/jquery-number-format/178/

回答by George

Another way to do it:

另一种方法:

function addCommas(n){
  var s = "",
      r;

  while (n) {
    r = n % 1000;
    s = r + s;
    n = (n - r)/1000;
    s = (n ? "," : "") + s;
  }

  return s;
}

alert(addCommas(12345678));

回答by pymarco

Here is my coffeescript version of @baacke's fiddle provided in a comment to @Timothy Perez

这是我在@Timothy Perez 的评论中提供的@baacke 小提琴的咖啡脚本版本

class Helpers
    @intComma: (number) ->
        # remove any existing commas
        comma = /,/g
        val = number.toString().replace comma, ''

        # separate the decimals
        valSplit = val.split '.'

        integer = valSplit[0].toString()
        expression = /(\d+)(\d{3})/
        while expression.test(integer)
            withComma = ","
            integer = integer.toString().replace expression, withComma

        # recombine with decimals if any
        val = integer
        if valSplit.length == 2
            val = "#{val}.#{valSplit[1]}"

        return val