将逗号放在Javascript整数中 [英] Place commas in Javascript integers
本文介绍了将逗号放在Javascript整数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在Javascript中有一个值:
So I have a value in Javascript:
var val = Entry.val;
此值的一个示例是 277385
。我如何在Javascript中将此数字转换为 277,385
,以及任何数字,以便在正确的位置使用逗号?
One example of this value is 277385
. How do I, in Javascript, convert this number to 277,385
, as well as any number to that so it has commas in the correct spots?
推荐答案
这应该适合你:
功能:
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;
}
用法:
addCommas(1000)
// 1,000
addCommas(1231.897243)
// 1,231.897243
感谢 mredjk.com
这篇关于将逗号放在Javascript整数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文