javascript 使用逗号格式化数字字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10810497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:06:45  来源:igfitidea点击:

Format number string using commas

javascriptregex

提问by user850234

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:

我想格式化数字。我看过一些在数字字符串中插入逗号的正则表达式示例。他们都检查一行中的 3 位数字,然后在数字中插入逗号。但我想要这样的东西:

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 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.

我对正则表达式很陌生。请帮助我如何显示上述数字。我试过下面的方法。这总是检查 3 位数字,然后添加逗号。

function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

But i want comma every 2 digits except for the last 3 digits before the decimals as shown above.

但我想要逗号每 2 位,除了小数点前的最后 3 位,如上所示。

回答by row1

The result will depend on your browsers locale. But this might be an acceptable solution:

结果将取决于您的浏览器区域设置。但这可能是一个可以接受的解决方案:

(7123456789.56742).toLocaleString();

Outputs:

输出:

7,123,456,789.56742

Try it and see if it outputs 7,12,34,56,789.567421in your locale.

尝试一下,看看它是否7,12,34,56,789.567421在您的语言环境中输出。

回答by KooiInc

Here's a function to convert a number to a european (1.000,00 - default) or USA (1,000.00) style:

这是一个将数字转换为欧洲 (1.000,00 - 默认) 或美国 (1,000.00) 样式的函数:

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] :'')
  ;
}

Alternative:

选择:

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

[editbased on comment] If you want to separate by 100, simply change i -= 4;to i -= 3;

[根据评论编辑]如果要以100分隔,只需更改i -= 4;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('');
  }
}

回答by Mily Dahlke

use toLocaleString(); It automatically handles inserting commas and will also handle uk strings the right way

使用 toLocaleString(); 它会自动处理插入逗号,也会以正确的方式处理 uk 字符串

e.g. var num=63613612837131; alert(num.toLocaleString());

例如 var num=63613612837131; alert(num.toLocaleString());

回答by Malcolm

Below is the snippet of code, can be done in better way but this works :D

以下是代码片段,可以以更好的方式完成,但这有效:D

function formatDollar(num) 
{
var p = num.toFixed(2).split(".");
var chars = p[0].split("").reverse();
var sep1000 = false;
var newstr = '';
var count = 0;
var count2=0;
for (x in chars) 
{ 
count++;
if(count%3 == 1 && count != 1 %% !sep1000) 
{ 
newstr = chars[x] + ',' + newstr;
sep1000=true;
} 
else 
{ 
if(!sep1000)
{
newstr = chars[x] + ',' + newstr;
}
else
{
count2++;
if(count%2 == 0 && count != 1) 
{ 
newstr = chars[x] + ',' + newstr;
} 
else 
{ 
 newstr = chars[x] + newstr;
}
}
}
}
return newstr + "." + p[1]; 
}