s6jfiw
Last Updated: February 25, 2016
·
4.768K
· ipetepete
522f44265e0ed80578f6d3af4cdf7011

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 ;)

Say Thanks
Respond

3 Responses
Add your response

1110
Profile 2015 2

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 ·
1123
over 1 year ago ·
1139
E000ba24fdfe2d8a847bb79dea812c9d

It's not limited to JavaScript however. And it has to do with the fact that the numbers are stored as fractionals like, but not limited to: 0.99999...

over 1 year ago ·