JS round to 2 decimal places [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-23 05:08:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!