在jQuery中将逗号添加到数字

2022-01-12 00:00:00 numbers formatting jquery javascript

我有这些号码

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,9998,094456

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

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

可以吗?

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

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/W5jwY/1/

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

打算看看新的全球化插件,以获得更好的方法

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

谢谢

杰米

推荐答案

适用于所有浏览器,这就是你所需要的.

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

感谢正则表达式,将其写得简洁明了.这是直接的 JS,但你可以像这样在 jQuery 中使用它:

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

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

但是,如果您需要更清洁、更灵活的东西.下面的代码将正确修复小数,删除前导零,并且可以无限使用.感谢评论中的@baacke.

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

在你的 jQuery 中,像这样使用:

And in your jQuery, use like so:

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

这里是 jsFiddle.

相关文章