Skip to the solution
MediumBackend12 min read

Why does 0.1 + 0.2 != 0.3 in Python, and when do you use Decimal or Fraction?

989 views

The problem

Question presented to candidate: "If I type 0.1 + 0.2 == 0.3 into Python I get False. Why does that happen, how should I compare floats, and when would you reach for decimal.Decimal or fractions.Fraction instead of float?"

What a strong answer should cover:

  • A Python float is a 64-bit IEEE 754 binary double (53 bits of precision, sys.float_info.mant_dig == 53); 0.1, 0.2 and 0.3 have no exact binary form, so each literal is stored as the nearest binary fraction and the sum lands on a different neighbour than 0.3
  • repr() prints the shortest string that round-trips, which is why 0.1 looks exact but Decimal(0.1) or (0.1).as_integer_ratio() reveals the real stored value
  • Compare with a tolerance (math.isclose, with abs_tol near zero), sum with math.fsum, and know that round() uses round-half-to-even on the stored binary value (round(2.675, 2) is 2.67)
  • Decimal does base-10 arithmetic with a configurable context (28 significant digits by default, explicit rounding modes, quantize for cents): the right tool for money, and it must be built from strings or ints, not floats
  • Fraction stores an exact numerator/denominator pair: exact for rational maths, but slower and its denominators can grow without bound
  • Trade-offs: float is hardware-fast and right for science and measurement; Decimal and Fraction refuse or downgrade when mixed with floats

Code / implementation expected: Optional β€” show the stored value of 0.1, a tolerant comparison, and a money calculation with Decimal and quantize.

  • float
  • decimal
  • numbers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWhat a float really stores: repr, exact value, isclose, fsum and round
PythonDecimal for money (quantize, context, rounding) and Fraction for exact ratios

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 55 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

Polars vs pandas: when should you switch in 2025-26?

Continue