在 jQuery 中为数字添加逗号

我有这些号码

109998094456

我想做的就是在正确的地方加一个逗号,如果需要的话,看起来就像这样

10,9998,094456

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

能做到吗?

我已经尝试在这里与其他职位的帮助 http://jsfiddle.net/pdWTU/1/,但似乎不能得到它的工作

谢谢

杰米

更新

胡闹了一会儿,终于在这里弄明白了

我们来看看新的全球化插件,找到一种更好的实现方法

谢谢

杰米

113409 次浏览

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

Take a look at recently released Globalization plugin to jQuery by Microsoft

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})/, '$1'+','+'$2');
}
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:

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

or

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

However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.

  function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals
    

while (/(\d+)(\d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}


if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }


return val;
}

And in your jQuery, use like so:

$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});

Here's the jsFiddle.

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

    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, "$1,") : b) + c;
});
}


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

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.

      $('#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>

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, '$1' + ',' + '$2');
}
return x1 + x2;
}
var a  = addCommas(10000.00);
alert(a);

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

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

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

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 = "$1,$2"
integer = integer.toString().replace expression, withComma


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


return val

Using toLocaleString ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

function formatComma(value, sep = 0) {
return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });
}
console.log(formatComma(123456789, 2)); // ¥123,456,789.00
console.log(formatComma(123456789, 0)); // ¥123,456,789
console.log(formatComma(1234, 0)); // ¥1,234