如何用逗号显示大数字?HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27761543/
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
How do I display large numbers with commas? HTML
提问by Cosmicluck
I am wanting to display large numbers more nicely with commas. So if the number was say 123456789, it would display 123,456,789. I have looked around but I only found code that just wouldn't work the way I wanted so I was hoping I could find some help here. Also, I hope it is also dynamic, so the commas will change as the number changes.
我想用逗号更好地显示大数字。所以如果数字是 123456789,它会显示 123,456,789。我环顾四周,但我只找到了无法按我想要的方式工作的代码,所以我希望我能在这里找到一些帮助。另外,我希望它也是动态的,所以逗号会随着数字的变化而变化。
The number that I want to affect has the id="value".
我想影响的数字有 id="value"。
That should be all, I don't think I am missing anything. So again I want the number with an id="value" to have commas introduced when it's needed. If you need any more information please let me know!
这应该是全部,我认为我没有遗漏任何东西。所以我再次希望带有 id="value" 的数字在需要时引入逗号。如果您需要更多信息,请告诉我!
采纳答案by Luis Eduardo Rojas Cabrera
This was answered here:
这是在这里回答:
How to print a number with commas as thousands separators in JavaScript
如何在 JavaScript 中使用逗号作为千位分隔符打印数字
In case you're not interested in reading the answer above, the code given was this:
如果你对阅读上面的答案不感兴趣,给出的代码是这样的:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
If you're using jquery use something like:
如果您使用 jquery,请使用以下内容:
var val = parseInt($('#value').text());
//Use the code in the answer above to replace the commas.
val = numberWithCommas(val);
$('#value').text(val);
回答by Oriol
回答by Nelson
There's a simpler syntax for toLocaleString:
toLocaleString有一个更简单的语法:
Number(x).toLocaleString();
This lets you drop the number in as a variable instead of converting the number into an object.
这使您可以将数字作为变量放入,而不是将数字转换为对象。