在jQuery中将逗号添加到数字

add commas to a number in jQuery(在jQuery中将逗号添加到数字)
本文介绍了在jQuery中将逗号添加到数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些号码

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.

这篇关于在jQuery中将逗号添加到数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)