Data Types

Floating Point Numbers and Why 0.1 Plus 0.2 Looks Wrong

By CodeRims Editorial Team · · 4 min read

Open a Python prompt, type 0.1 + 0.2, and press Enter. Instead of 0.3, you see 0.30000000000000004. JavaScript, Java, C, and many other languages produce the same result. New programmers often assume the language has a bug.

It does not. The behavior comes from how computers store decimal fractions, and once you understand it, the result stops being strange. This article explains what is going on and how to handle such numbers in real code.

The Surprise

Here is the example in code.

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)

The first line prints 0.30000000000000004. The second prints False. Mathematically, one tenth plus two tenths is exactly three tenths. The computer disagrees, but only by an extremely small amount.

Why It Happens

Computers store numbers in binary, using only ones and zeros. Whole numbers convert to binary cleanly. Fractions are trickier.

Think about writing one third in decimal. You get 0.3333 and so on, repeating forever. No finite number of digits is exact. Our decimal system simply cannot express one third precisely.

Binary has the same problem with different fractions. A binary fraction can exactly represent values like one half, one quarter, and one eighth, because they are powers of two. But one tenth is not a power of two fraction. In binary, 0.1 becomes an endless repeating pattern, just as one third does in decimal.

Since the computer has limited space, it stores only the closest value it can fit. So the stored number for 0.1 is very slightly off, and so is the stored number for 0.2. When you add them, those tiny errors combine, and the result is a hair away from the stored value for 0.3.

What Floating Point Means

The scheme most languages use is called floating point, standardized as IEEE 754. A number is stored in a form like scientific notation: a sign, a significand holding the digits, and an exponent that says where the point sits. The word "floating" refers to the point moving depending on the exponent.

The common format, called double precision, uses 64 bits. That gives a large range and roughly fifteen to seventeen significant decimal digits of precision. It is excellent for science, graphics, and most calculations. The cost is that many decimal fractions cannot be stored exactly.

Rules of Thumb

Once you know the cause, a few practical rules follow.

  1. Never compare floats for exact equality unless you are certain the values are exactly representable.
  2. Expect tiny errors in the last digits after arithmetic.
  3. Errors can accumulate. Adding a small number many times in a loop can drift further from the true answer.
  4. Integers are exact within their range, which gives you a useful alternative for some cases.

Comparing Floats Safely

Instead of checking equality, check whether two numbers are close enough. Most languages provide a helper. In Python, you can use math.isclose.

import math

print(math.isclose(0.1 + 0.2, 0.3))

This prints True. The function compares the difference against a small tolerance. You can also write your own check by testing whether the absolute difference is smaller than a chosen limit, which should suit the scale of your numbers.

Working With Money and Exact Decimals

Whenever values must be exactly decimal, such as amounts of currency or measurements recorded to fixed places, ordinary floats are a poor choice. Two common approaches work better.

Use integers in the smallest unit. Store amounts as a whole number of the smallest unit, for example counting in cents instead of dollars with fractions. Integer arithmetic is exact, and you convert for display only.

Use a decimal type. Many languages offer a decimal type that stores numbers in base ten. Python includes one in its standard library.

from decimal import Decimal

print(Decimal("0.1") + Decimal("0.2"))

This prints 0.3 exactly. Note that you pass the values as strings. Creating a Decimal from the float 0.1 would carry over the float's inexactness.

Decimal types are slower than floats and use more memory, so they suit situations where exactness matters more than raw speed.

Rounding and Displaying

Often you do not need to fix the value, only to show it sensibly. Formatting a number to a fixed number of decimal places hides the tiny error.

print(f"{0.1 + 0.2:.2f}")

This prints 0.30. Keep in mind that rounding for display is different from rounding the stored value. Be deliberate about which one you mean, and decide where rounding should happen in a calculation chain.

Other Float Surprises

The same system produces a few more oddities worth knowing.

  • Very large and very small numbers lose precision. Adding a tiny value to a huge one may change nothing.
  • Special values exist. Floats can represent infinity and a "not a number" value, which results from operations such as zero divided by zero in some languages. A not-a-number value is not equal to anything, even itself.
  • Order of operations matters. Adding numbers in a different order can give slightly different results.

None of these are bugs. They follow from finite precision and are consistent across systems that follow the standard.

Frequently Asked Questions

Is this a bug in my programming language?

No. It is a consequence of storing decimal fractions in binary with limited space. Nearly every language that uses standard floating point behaves the same way.

Should I stop using floats?

No. Floats are the right tool for most numerical work, such as measurements, physics, and graphics. Switch to integers or decimal types only when you need exact decimal results, as with money.

How do I check whether two floats are equal?

Compare them with a tolerance instead of using exact equality. Use a helper such as math.isclose in Python or compute whether the absolute difference is smaller than a small threshold suited to your data.

Related reading