Why 0.1 + 0.2 Doesn't Equal 0.3
In binary, 0.1 is a repeating fraction — like 1/3 in decimal. The computer has to round.
Open a JavaScript console. Type 0.1 + 0.2. The answer is 0.30000000000000004. Python gives you the same thing. So does C, Java, Swift, Go — any language that follows the IEEE 754 floating-point standard, which is almost all of them.
The reason is base 2. Decimal numbers like 0.1 assume ten fingers. Computers have two. In binary, one-tenth is a repeating fraction — 0.0001100110011... forever — the same way one-third is 0.333... in decimal. You have to cut it off somewhere.
IEEE 754 cuts it off at 52 bits of significand, giving you about 15-17 decimal digits of precision. So 0.1 becomes slightly more than 0.1, and 0.2 becomes slightly more than 0.2, and when you add them you get something slightly more than 0.3. The specific value that comes out — 0.30000000000000004 — is the nearest representable double to the true sum.
This is why financial code uses decimal types or integer cents, and why writing if (x == 0.3) after a calculation is a bug waiting to happen. The standard was finalized in 1985, and every attempt to replace it has failed on the same grounds: hardware support.
Make Recess yours.
Sign in to save the ones you loved, never see the same thing twice, and tell us what you want more of.