使用逗号格式化数字字符串 [英] Format number string using commas
问题描述
我想格式化数字。我已经看到了一些在数字字符串中插入逗号的正则表达式表达式示例。所有这些都连续检查3位数,然后在数字中插入逗号。但我想要这样的事情:
I want to format numbers. I have seen some of the regex expression example to insert comma in number string. All of them check 3 digits in a row and then insert comma in number. But i want something like this:
122 as 122
1234 as 1,234
12345 as 12,345
1723456 as 17,23,456
7123456789.56742 as 7,12,34,56,789.56742
I我是正则表达式的新手。请帮我如何显示如上所示的数字。我尝试过以下方法。这总是检查3位数,然后添加逗号。
I am very new to regex expression. Please help me how to display the number as the above. I have tried the below method. This always checks for 3 digits and then add comma.
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
但除了小数点前的最后3位数,我想要每两位数逗号如上所示。
But i want comma every 2 digits except for the last 3 digits before the decimals as shown above.
推荐答案
这是一个将数字转换为欧洲(1.000,00 - 默认)或美国(1,000.00)的函数)style:
Here's a function to convert a number to a european (1.000,00 - default) or USA (1,000.00) style:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return dec[0]
.split('')
.reverse()
.reduce(function(prev,now,i){
return i%3 === 0 ? prev+sep+now : prev+now;}
)
.split('')
.reverse()
.join('') +
(dec[1] ? decsep+dec[1] :'')
;
}
替代方案:
function sep1000(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 4;
}
return n.join('');
}
}
//usage for both functions
alert(sep1000(10002343123.034)); //=> 10.002.343.123,034
alert(sep1000(10002343123.034,true)); //=> 10,002,343,123.034
[编辑基于评论]如果你想要100分开,只需将 i - = 4;
更改为 i - = 3;
[edit based on comment] If you want to separate by 100, simply change i -= 4;
to i -= 3;
function sep100(somenum,usa){
var dec = String(somenum).split(/[.,]/)
,sep = usa ? ',' : '.'
,decsep = usa ? '.' : ',';
return xsep(dec[0],sep) + (dec[1] ? decsep+dec[1] :'');
function xsep(num,sep) {
var n = String(num).split('')
,i = -3;
while (n.length + i > 0) {
n.splice(i, 0, sep);
i -= 3; //<== here
}
return n.join('');
}
}
这篇关于使用逗号格式化数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!