javascript JS四舍五入到小数点后两位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32300649/
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
JS round to 2 decimal places
提问by user2344148
I am trying to limit the returned number to be only 2 decimal places but this code isn't working for me;
我试图将返回的数字限制为只有 2 个小数位,但此代码对我不起作用;
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "Result is: " + x * 1.09; value = valToRound.toFixed(2);
}
}
What am I doing wrong?
我究竟做错了什么?
回答by Paul
Typing in the JS Browser console
在 JS 浏览器控制台中输入
x = 2.71828
x.toFixed(2)
"2.72"
it is clear that .toFixed(2)
works
很明显.toFixed(2)
有效
What you did wrong was rounding afterprinting the answer, and not using the correct variables.
您做错的是在打印答案后四舍五入,而不是使用正确的变量。
document.getElementById("demo").innerHTML = "Result is: " + x * 1.09; value = valToRound.toFixed(2);
It is also a good idea to get in the habit of converting strings to numbers with parseFloat()
. In JS, '2'*'2' is '4' but '2'+'2' is '22', unless you first convert to number.
养成将字符串转换为数字的习惯也是一个好主意parseFloat()
。在 JS 中,'2'*'2' 是 '4' 但 '2'+'2' 是 '22',除非您先转换为数字。
If you do it this way it will work:
如果您这样做,它将起作用:
function myFunction() {
var x = parseFloat(document.getElementById("mySelect").value);
var valToRound = x * 1.09;
var value = valToRound.toFixed(2);
document.getElementByID("demo").innerHTML = "Result is: " + value;
}