How Computers Store Decimals and Why 0.1 Plus 0.2 Looks Wrong
Find out why 0.1 plus 0.2 prints an odd tail, how binary floating point stores numbers, and how to compare and total safely.
Key takeaways
- Most computers store non-whole numbers in binary floating point, which keeps a limited number of significant bits.
- One tenth is an endlessly repeating pattern in binary, so it must be rounded before any arithmetic starts.
- Test floating-point results for closeness within a tolerance, not for exact equality.
- For money and other exact decimal quantities, use whole-number units or a decimal number type.
In many programming languages, adding 0.1 and 0.2 gives 0.30000000000000004. The computer is adding correctly. The catch is that it never held exactly 0.1 or 0.2 in the first place, because neither has a finite expansion in binary, and the machine keeps only a fixed number of binary digits.
Each input is rounded to the nearest storable value, the sum is rounded again, and the tiny errors become visible when the result is printed with enough digits.
Fractions that never end
You already know this problem from decimal. One third is 0.3333..., and if you may keep only five places, you store 0.33333. Three copies add up to 0.99999, not 1.
Which fractions end depends on the base. In lowest terms, a fraction has a finite expansion only if every prime factor of its denominator divides the base. Base ten allows denominators made of 2s and 5s. Base two allows only 2s. So 1/2, 3/8 and 5/64 are exact in binary, while 1/10, which has a factor of 5 below, is not.
You can generate the binary digits of 0.1 by doubling and recording the whole-number part each time.
0.1 × 2 = 0.2 digit 0
0.2 × 2 = 0.4 digit 0
0.4 × 2 = 0.8 digit 0
0.8 × 2 = 1.6 digit 1, keep 0.6
0.6 × 2 = 1.2 digit 1, keep 0.2
0.2 × 2 = 0.4 digit 0, and the cycle repeats
0.1 = 0.000110011001100110011... in binary The block 0011 repeats forever. If binary notation is new to you, start with binary numbers and their arithmetic.
Floating point is binary scientific notation
In scientific notation you write a number as a few significant digits times a power of ten, such as 6.25 × 10³. Floating point does the same with powers of two. The point "floats" because the exponent decides where it falls.
The widely used standard is called IEEE 754. Its common 64-bit format, often named double precision, splits the bits into three fields.
| Field | Bits | Role |
|---|---|---|
| Sign | 1 | Positive or negative |
| Exponent | 11 | The power of two |
| Fraction | 52 | Digits after the leading 1 |
For ordinary (normalized) numbers the leading bit is always 1, so it need not be stored, which gives 53 significant bits. That works out to roughly 15 to 17 significant decimal digits. The 32-bit single precision format has 24 significant bits, or about 7 decimal digits.
What happens in 0.1 plus 0.2
When you type 0.1, the computer chooses the closest double. Its value, to twenty decimal places, is 0.10000000000000000555. The closest double to 0.2 is about 0.20000000000000001110. Both are slightly too large.
The machine adds these two values and then rounds the sum to a double. The result is about 0.30000000000000004441.
Now type 0.3. Its closest double is about 0.29999999999999998890, which is slightly too small. The two results are neighboring doubles, but they are different ones, so a test such as 0.1 + 0.2 == 0.3 returns false.
- Round 0.1 to binary (a little high).
- Round 0.2 to binary (a little high).
- Add and round the sum (ends up high).
- Compare with 0.3 rounded on its own (a little low).
Printing hides much of this. Many languages display the shortest decimal string that would be read back as the same double. For the stored 0.1 that string is "0.1". For the sum it needs seventeen significant digits to be distinguishable from 0.3.
The gaps between numbers
There are only finitely many doubles, so there are gaps between neighbors. The gaps scale with size: they are extremely fine near zero and coarse for huge values. What stays roughly constant is the relative precision, about one part in 10¹⁶.
This has a surprising consequence for whole numbers. Every integer up to 2⁵³ = 9,007,199,254,740,992 can be stored exactly. The next one, 2⁵³ + 1, cannot, because the spacing there has become 2. Adding 1 to 2⁵³ in double precision gives back 2⁵³.
Large integer identifiers can therefore be corrupted if software passes them through a floating-point type. Store them as true integers or as text.
When the usual rules bend
In exact arithmetic, regrouping a sum never changes it. In floating point, rounding happens after every step, so grouping matters.
(0.1 + 0.2) + 0.3 gives 0.6000000000000001
0.1 + (0.2 + 0.3) gives 0.6 Swapping the order of two numbers being added still gives the same result, but the associative property described in the basic laws of arithmetic fails.
Two situations magnify trouble. The first is absorption: adding a tiny number to a huge one may leave the huge one unchanged. Adding many small terms from smallest to largest usually preserves more of them. The second is cancellation: subtracting two nearly equal numbers removes the leading digits they share and leaves mostly the rounding noise. If two values agree in their first twelve digits, their difference has only a few trustworthy digits left. How such errors accumulate is the subject of rounding error growth.
Two surprises worth working through
Rounding that seems to go the wrong way. In Python, round(2.675, 2) returns 2.67, although school rounding suggests 2.68. The stored double nearest to 2.675 lies slightly below it, so there is no true tie to break. When a value really is exactly halfway, such as 2.5 rounded to a whole number, many systems use "round half to even" and return 2, while 3.5 becomes 4. Rounding ties to the even neighbor avoids a steady upward drift in long totals.
A formula that loses digits. Suppose you want the difference √(x + 1) − √x for a very large x. The two square roots agree in most of their digits, so subtracting them cancels the reliable part. Multiply top and bottom by the sum of the roots and you get an equivalent expression:
√(x + 1) − √x = 1 ÷ (√(x + 1) + √x) for x ≥ 0 The right side adds two positive numbers and then divides, so nothing cancels. The same trick helps with the quadratic formula when one root is much smaller than the other. You compute the larger root first, then use the fact that the product of the two roots equals c/a to get the smaller one by division.
Neither fix needs extra precision. Each one arranges the arithmetic so that the rounding errors already present are not magnified.
Comparing and totaling safely
Ask whether two results are close enough, where "enough" depends on your problem.
close if |a − b| ≤ tolerance × max(|a|, |b|) This relative test works well away from zero. Near zero you also need a small absolute tolerance, since nothing is relatively close to 0 except 0 itself. Many languages provide a library function for this, such as math.isclose in Python.
Further habits help.
- Do not control a loop by stepping a floating-point counter until it equals a target. Count with integers and compute the value from the count.
- Round only for display or at points your rules require, not after every step.
- Be careful when subtracting similar quantities. Algebra can often rearrange the formula to avoid it.
Money and exact decimals
Prices are exact decimal amounts, and people expect cents to add up. Two standard approaches work.
Count in the smallest unit. Store 1999 cents instead of 19.99 dollars. Integer addition is exact, as long as the values stay within the integer type's range. You still need a stated rounding rule for operations like percentages and splits. Dividing 100 cents among three people leaves one cent to assign.
Use a decimal type. Many languages and databases offer decimal numbers that store base-ten digits. In them, 0.1 plus 0.2 is exactly 0.3. They still cannot hold 1/3 exactly, and they are usually slower than hardware binary floating point.
Fraction types, which keep a numerator and denominator as integers, are exact for rational numbers but their digits can grow large. None of these can store most irrational numbers such as √2 exactly in digit form.
Common questions
Why does a calculator seem to get this right?
Many calculators work in decimal internally, or keep a few more digits than they display and round before showing the result. Either way the tiny discrepancy stays out of sight. It does not follow that every calculator result is exact: dividing 1 by 3 still has to be cut off somewhere.
Do whole numbers have the same problem?
Whole numbers stored as integers are exact, as long as they stay within the range of the type. Their hazard is different. A fixed-size integer that exceeds its limit may wrap around to a wrong value or raise an error, depending on the language. Some languages offer integers that grow as large as memory allows.
Can I fix it by rounding at the end?
For display, usually yes. Rounding the final answer to two places turns 0.30000000000000004 into 0.30. It is not a cure for decisions made along the way, such as an equality test inside a loop, or for sums where thousands of small errors have piled up before you round.
Special values and common myths
The standard also defines special values. Overflow can produce infinity. Undefined operations such as 0/0 produce NaN, meaning "not a number," which compares as unequal to everything, including itself. There are even two zeros, positive and negative, which test as equal.
A few myths are worth clearing away. Floating point is not random: under the same operations in the same order with the same rounding settings, it gives the same answer. Nor is this a flaw of one language, since nearly all of them use the processor's IEEE 754 arithmetic. And more precision does not cure it. Extra bits make the error smaller, but one tenth remains an infinite pattern in binary.
For most physics and engineering work, double precision is far finer than the measurements going in. Problems arise when code assumes exactness, or when an unstable calculation lets small errors grow. Know which kind of number you hold, and the strange tail after 0.3 stops being a mystery.