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

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

How do I round to 2 decimal places?

javascriptmath

提问by Patrick R

I have a number with a comma, for example: 254,5. I need the 0behind the ,5so it stands like 254,50instead..

我有一个带逗号的数字,例如:254,5。我需要0后面的,5所以它看起来像254,50相反..

I'm using this to get the number:

我正在使用它来获取号码:

Math.floor(iAlt / 50) * 50;

How can i get the 0behind the ,5?

我怎样才能得到0后面的,5

回答by Matt

Try the toFixed()method, which pads the decimal value to length nwith 0's.

尝试使用 0toFixed()将十进制值填充到长度n的方法。

var result = (Math.floor(iAlt / 50) * 50).toFixed(2);

A Numberwill always remove trailing zeros, so toFixedreturns a String.

ANumber将始终删除尾随零,因此toFixed返回 a String

It's important to note that toFixedmustbe 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()将字符串转换为数字(不是在这种情况下,而是供将来参考)。