在jQuery中添加逗号给一个数字 [英] add commas to a number in jQuery

查看:151
本文介绍了在jQuery中添加逗号给一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些数字

10999 8094 456



我所要做的就是在正确的地方添加一个逗号它看起来像这样



10,999 8,094 456



这些都在ap标签内,如< p class =points > 10999< / p> 等等



可以这样做吗? >我在这里尝试过,在其他帖子的帮助下 http://jsfiddle.net/pdWTU/1/ ,但似乎无法得到它的工作



谢谢

杰米



更新

有一点点设法弄清楚了 http://jsfiddle.net/W5jwY/1/



去看看新的全球化插件更好的做法



谢谢

Jamie 解决方案

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

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



$ b $ p
$ b

写这个是紧凑的,而且要归功于正则表达式。这是直的JS,但你可以像你这样在你的jQuery中使用它:

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

  $( '#inputID')VAL(commaSeparateNumber(1234567890))。; 


I have these numbers

10999 and 8094 and 456

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

10,999 and 8,094 and 456

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

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

Thanks

Jamie

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

Thanks

Jamie

解决方案

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

这篇关于在jQuery中添加逗号给一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆