Why does toFixed () act like this in Javascript?
In this example / the behavior is something very strange.
Why toFixed
does the function for the first two examples work, but not for this last one?
//example 1
var num = 554.956;
var n = num.toFixed(2)
console.log(n);
var num2 = 554.955;
var n2 = num2.toFixed(2)
console.log(n2);
//output 554.96 and 554.96
//example 2
var num5 = 5.956;
var n5 = num5.toFixed(2)
console.log(n5);
var num6 = 5.955;
var n6 = num6.toFixed(2)
console.log(n6);
//output 5.96 and 5.96
//example 3
var num3 = 55.956;
var n3 = num3.toFixed(2)
console.log(n3);
var num4 = 55.955;
var n4 = num4.toFixed(2)
console.log(n4);
//output 55.96 and 55.95
Related to: php round vs javascript toFixed
EDIT: about duplicates, especially this one: the toFixed function does not work as expected (please provide a reason not an alternative)
The answer is very good and helps to understand the difference between x.955 and x.956, but does not answer why this only happens with 55.955
in my example and not with 5.955
or 554.955
.
source to share
No one has answered this question yet
See similar questions:
or similar: