Reputation: 1
Different types of rounding and different result
Why is it, I was checking the mathematics rules, where was saying that after 0.5 we are rounding to 1 but in the second operation rounded to 0 and gives me the wrong answer
Upvotes: -1
Views: 111
Reputation: 71
The documentation for Number.prototype.toFixed() describes what's happening in this exact case: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
2.34.toFixed(1); // '2.3'
2.35.toFixed(1); // '2.4'; it rounds up
2.55.toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
2.449999999999999999.toFixed(1); // '2.5'
// it rounds up as it's less than NUMBER.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45
Upvotes: 0