Javascript toFixed function

Sushovan Mukherjee picture Sushovan Mukherjee · Jan 13, 2014 · Viewed 8.3k times · Source

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?

Answer

Denys Séguret picture Denys Séguret · Jan 13, 2014

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 :

(5.175 + 0.00001).toFixed(2)