Last Updated: August 14, 2019
·
6.089K
· ipetepete

0.1 + 0.2 !== 0.3 WTF?

Don't take my word for it, try it in the console.

(its actually 0.30000000000000004) <- for teh lazies

Here is a tip that might prevent some headaches in the future.

When doing floating point math, add some extra checks, such as rounding off the number or checking for the difference as well.

There is an issue with floating point math and computers in general, and you may not get the desired results without some safeguards. You can read more about it here:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

TL;DR

Basically your computer does math with 1's and 0's. It is really hard to represent certain (floating point) numbers with binary. It makes mistakes ;)

2 Responses
Add your response

That's really bad. :)
In JavaScript you can use Number#toFixed method, like that:

Number((0.1 + 0.2).toFixed(2)) === 0.3
# true
over 1 year ago ·
over 1 year ago ·