问题
I am trying to limit the returned number to be only 2 decimal places but this code isn't working for me;
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?
回答1:
Typing in the JS Browser console
x = 2.71828
x.toFixed(2)
"2.72"
it is clear that .toFixed(2)
works
What you did wrong was rounding after printing 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.
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;
}
来源:https://stackoverflow.com/questions/32300649/js-round-to-2-decimal-places