Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.round Rounding Error

I Want to round 1.006 to two decimals expecting 1.01 as output

When i did

var num = 1.006;
alert(Math.round(num,2)); //Outputs 1 
alert(num.toFixed(2)); //Output 1.01

Similarly,

var num =1.106;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2));; //Outputs 1.11

So

  • Is it safe to use toFixed() every time ?
  • Is toFixed() cross browser complaint?

Please suggest me.

P.S: I tried searching stack overflow for similar answers, but could not get proper answer.

EDIT:

Why does 1.015 return 1.01 where as 1.045 returns 1.05

var num =1.015;
alert(num.toFixed(2)); //Outputs 1.01
alert(Math.round(num*100)/100); //Outputs 1.01

Where as

var num = 1.045;
alert(num.toFixed(2)); //Outputs 1.04
alert(Math.round(num*100)/100); //Outputs 1.05
like image 770
Sudarshan Avatar asked Feb 27 '13 17:02

Sudarshan


1 Answers

Try something like...

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

from: http://www.javascriptkit.com/javatutors/round.shtml

(to round any number to x decimal points)

like image 176
John K. Avatar answered Sep 28 '22 06:09

John K.