使用 Javascript 格式化逗号和小数位的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30108219/
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
Formatting numbers for commas and decimal places with Javascript
提问by Jonathan Bechtel
I'm trying to create a function with javascript that displays all numbers with two decimal points and adds commas every three digits (1,000 10,000 100,000 etc).
我正在尝试使用 javascript 创建一个函数,该函数显示所有带有两个小数点的数字,并每三位数字添加一个逗号(1,000 10,000 100,000 等)。
At first I had this:
起初我有这个:
var formatNumber = function(num) {
return parseFloat((num).toFixed(2)).toLocaleString();
};
This works very well but with one exception.
这非常有效,但有一个例外。
1.2 != 1.20 in the final output. It just shows up as 1.2
1.2 != 1.20 在最终输出中。它只是显示为 1.2
But everything else is good. 124.5879697 = 124.59, 10000 = 10,000, and 10586.357 = 10,586.36
但其他一切都很好。124.5879697 = 124.59、10000 = 10,000 和 10586.357 = 10,586.36
The issue is the final output is going to display as money, so displaying 10000 as $10,000 is fine. But displaying 1.2 as $1.2 looks a little off.
问题是最终输出将显示为货币,因此将 10000 显示为 10,000 美元就可以了。但是将 1.2 显示为 1.2 美元看起来有点不对劲。
To get around this I tried to add the following modification:
为了解决这个问题,我尝试添加以下修改:
var formatNumber = function(num) {
return parseFloat((Math.round(num*100)/100)).toFixed(2).toLocaleString();
};
This carries everything out to two decimal places, which is fine, but it seems to have de-activated toLocaleString because now nothing displays commas.
这将所有内容都保留到两个小数位,这很好,但它似乎已停用 toLocaleString 因为现在没有任何显示逗号。
I'm looking to use pure Javascript with this and not jQuery. It seems there are a lot of js questions on this topic about one or the other issue, but not combining both.
我希望使用纯 Javascript 而不是 jQuery。关于这个主题,似乎有很多关于一个或另一个问题的 js 问题,但没有将两者结合起来。
Thank you.
谢谢你。
回答by Katerina Pavlenko
This seems to work
这似乎有效
var f = function(num) {
return parseFloat(num).toFixed(2).toLocaleString();
};