Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript toFixed function

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?

like image 407
Sushovan Mukherjee Avatar asked Jan 13 '14 12:01

Sushovan Mukherjee


1 Answers

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)
like image 83
Denys Séguret Avatar answered Oct 02 '22 19:10

Denys Séguret