Math.round舍入误差

Sud*_*han 6 javascript math rounding

我想要舍入1.006到两位小数,期望输出为1.01

当我做的时候

var num = 1.006;
alert(Math.round(num,2)); //Outputs 1 
alert(num.toFixed(2)); //Output 1.01
Run Code Online (Sandbox Code Playgroud)

同样的,

var num =1.106;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2));; //Outputs 1.11
Run Code Online (Sandbox Code Playgroud)

所以

  • 每次使用toFixed()是否安全?
  • 是toFixed()跨浏览器投诉?

请建议我.

PS:我尝试搜索堆栈溢出类似的答案,但无法得到正确的答案.

EDIT:

为什么1.015返回1.01,其中1.045返回1.05

var num =1.015;
alert(num.toFixed(2)); //Outputs 1.01
alert(Math.round(num*100)/100); //Outputs 1.01
Run Code Online (Sandbox Code Playgroud)

在哪里

var num = 1.045;
alert(num.toFixed(2)); //Outputs 1.04
alert(Math.round(num*100)/100); //Outputs 1.05
Run Code Online (Sandbox Code Playgroud)

Joh*_* K. 5

试试像......

Math.round(num*100)/100


1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x
Run Code Online (Sandbox Code Playgroud)

来自:http://www.javascriptkit.com/javatutors/round.shtml

(将任意数字舍入到x小数点)

  • @nlsbshtr:[浮点错误](http://stackoverflow.com/questions/1458633/elegant-workaround-for-javascript-floating-point-number-problem)似乎有问题。 (2认同)