javascript 如何四舍五入到小数点后两位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8225558/
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 round to 2 decimal places?
提问by Patrick R
I have a number with a comma, for example: 254,5
. I need the 0
behind the ,5
so it stands like 254,50
instead..
我有一个带逗号的数字,例如:254,5
。我需要0
后面的,5
所以它看起来像254,50
相反..
I'm using this to get the number:
我正在使用它来获取号码:
Math.floor(iAlt / 50) * 50;
How can i get the 0
behind the ,5
?
我怎样才能得到0
后面的,5
?
回答by Matt
Try the toFixed()
method, which pads the decimal value to length n
with 0's.
尝试使用 0toFixed()
将十进制值填充到长度n
的方法。
var result = (Math.floor(iAlt / 50) * 50).toFixed(2);
A Number
will always remove trailing zeros, so toFixed
returns a String
.
ANumber
将始终删除尾随零,因此toFixed
返回 a String
。
It's important to note that toFixed
mustbe called on a number. Call parseFloat()
or parseInt()
to convert a string to a number first, if required (not in this situation, but for future reference).
重要的是要注意,toFixed
必须在一个号码上调用。如果需要,首先调用parseFloat()
或parseInt()
将字符串转换为数字(不是在这种情况下,而是供将来参考)。