The expected result of:
(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18
But in JS showing:
(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*
How to rectify the problem?
The expected result of:
(1.175).toFixed(2) = 1.18 and
(5.175).toFixed(2) = 5.18
But in JS showing:
(1.175).toFixed(2) = 1.18 but
*(5.175).toFixed(2) = 5.17*
How to rectify the problem?
You could always try using round, instead of toFixed.
Math.round(5.175*100)/100
You could even try putting it in some prototype method if you want.
Created a jsBin that implements a simple prototype on Number.
It's because the numbers are stored as IEEE754.
I would recommend you to use the Math class (round, floor or ceil methods, depending on your needing).
I've just created a class MathHelper that can easily solve your problem:
Usage:
Demo: http://jsfiddle.net/v2Dj7/
It's not a bug. It's related to the fact numbers aren't stored in decimal but in IEEE754 (so
5.175
isn't exactly stored).If you want to round in a specific direction (up) and you consistently have numbers of this precision, you might use this trick :
Kippie your solution has problems one of them
this works good)
// "5.18"
Actually I think this is a bug in the implementation of
Number.prototype.toFixed
. The algorithm given in ECMA-262 20.1.3.3 10-a says to round up as a tie-breaker. As others have mentioned, there probably isn't a tie to break due to floating point imprecisions in the implementation. But that doesn't make it right :)At least this behavior is consistent across FF, Chrome, Opera, Safari. (Haven't tried others.)
FWIW, you can actually implement your own version of
toFixed
per the spec in JS and that behaves as you would expect. See http://jsfiddle.net/joenudell/7qahrb6d/.