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
Math.round
rounds to the nearest integer. – Brae1.015*100
gives you101.49999999999999
instead of101.5
, causing it to round down instead of up. – Monkfish