Javascript Angular:用逗号格式化数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44929282/
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-08-23 02:47:32  来源:igfitidea点击:

Angular: Formatting numbers with commas

javascriptangulartypescript

提问by BeingSuman

Title very much sums up my needs.

标题非常概括了我的需求。

123456789 => 123,456,789
12345 => 12,345

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

获得这种转换的最佳方法是什么?不要在 Angular-2 中建议使用货币管道,因为我不需要将 $ 或货币符号添加到我的输出中。

回答by CodeWarrior

Use DecimalPipe like this

像这样使用 DecimalPipe

{{attr | number}}

{{attr | number}}

Working Plunker

工作Plunker

Documentation available at https://angular.io/api/common/DecimalPipe

文档可在https://angular.io/api/common/DecimalPipe

回答by JGFMK

function printNo() {
  document.getElementById('text').innerHTML =
  Number(1234355).toLocaleString('en-GB');
}
 <!DOCTYPE html>
 <html>
    <head></head>
    
     <body onload="printNo()">
      <h1 id="text"></h1>
        
     </body>
</html>

Reference link

参考链接

回答by Sebastian Giro

Without using pipes, a simple way to answer your question with javascript:

在不使用管道的情况下,使用 javascript 回答您的问题的简单方法:

var str = "The quick brown fox jumps over the lazy dogs.".replace(/(.{2})/g,",");

And this will output Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.

这将输出 Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.

But I think you formulated your question bad, so, If you want to parse numbers, you should use this function:

但我认为你的问题表述得很糟糕,所以,如果你想解析数字,你应该使用这个函数:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

So

所以

var num = numberWithCommas(1234567);
console.log(num);

This will output 1,234,567

这将输出 1,234,567