我有这些数字

109998094456

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

10,999 and 8,094 and 456

这些都在一个p标签内,比如<p class="points">10999</p>等等.

这事办得到吗?

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

谢谢

杰米

UPDATE

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

谢谢

杰米

推荐答案

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

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

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

However, if you require something cleaner, with flexibility. The below code will fix decimals c或rectly, 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.

Jquery相关问答推荐

为什么如果使用转换规模,juserui可拖动遏制不起作用

如果链接包含多个关键字,jQuery 将 HTML 添加到链接

用 jQuery/JavaScript 检测数字或字母?

如何使 jQuery.ready 中定义的函数在全局可用?

jQuery在点击函数后获取
  • 元素的id/value
  • 如何在 jquery 中包含 !important

    Bootstrap 4 多选下拉菜单

    为什么要两次声明 jQuery?

    Backbone.js 和 jQuery

    如何在 HTML选项标签上显示工具提示?

    按值对 Html Select 的选项进行排序的最有效方法是什么,同时保留当前选定的项目?

    使用 jquery/ajax 刷新/重新加载 Div 中的内容

    我可以将 Nuget 保留在 jQuery 1.9.x/1.x 路径上(而不是升级到 2.x)吗?

    如何在 jquery 中更新(附加到)href?

    addClass - 可以在同一个 div 上添加多个类吗?

    jQuery:value.attr 不是函数

    在jquery中查找具有某个属性值的所有元素

    如何在 Bootstrap 中创建切换按钮

    javascript jquery单选按钮单击

    Bootstrap datepicker Select 后隐藏