Why 0.1 + 0.2 Is Not 0.3
Open almost any programming language and type 0.1 + 0.2. Python, JavaScript, Java and C all agree on the answer: 0.30000000000000004. It is not a bug in the language. It is what happens when you write decimal fractions with binary digits, and every programmer who works with measurements or money needs to understand it.
The rule
Binary fractions are sums of halves; 0.1 is not, so it is rounded.
After the binary point, the places are worth ½, ¼, ⅛, 1/16 and so on, each half of the one before:
binary 0.1 = 1/2 = decimal 0.5
binary 0.011 = 1/4 + 1/8 = decimal 0.375
decimal 0.1 = binary 0.0001100110011… (repeats forever)A number is exact in binary only if it can be built from a finite sum of these halves. In other words, written as a fraction in lowest terms, its denominator must be a power of two: ½, ¾, ⅝ and 3/16 are fine.
A tenth has denominator 10 = 2 × 5. That factor of 5 makes the binary pattern repeat forever, just as 1/3 = 0.3333… repeats forever in decimal. A computer keeps only a fixed number of bits, so it stores the nearest value it can. The stored "0.1" is a tiny bit more than 0.1, the stored "0.2" is too, and their sum lands just above the value stored for 0.3.
The error is tiny, around the 17th significant digit. It becomes a problem when you test for exact equality, or when millions of small errors pile up.