🎓 A1Learner
🔍
0 of 52 lessons completed

Python Exact Numbers: decimal and fractions

Decimal and Fraction are exact number types. They store numbers as written, not as near guesses.

The pain first: 0.1 + 0.2

Plain floats add 0.1 and 0.2. The answer misses 0.3 by a tiny error.

print(0.1 + 0.2)

Decimal fixes the tenth

Decimal("0.1") stores the tenth exactly. The sum prints as 0.3.

from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))

Add money exactly

Three prices add to 25.48. No stray digits appear.

from decimal import Decimal
total = Decimal("19.99") + Decimal("4.50") + Decimal("0.99")
print(total)

Exact parts with Fraction

A half plus a third is five sixths. Two quarters make a half.

from fractions import Fraction
print(Fraction(1, 2) + Fraction(1, 3))
print(Fraction(1, 4) + Fraction(1, 4))

Example

from decimal import Decimal
from fractions import Fraction
prices = [Decimal("2.50"), Decimal("1.20"), Decimal("0.30")]
total = Decimal("0")
for price in prices:
    total = total + price
print("Total:", total)
print("Half a cup:", Fraction(3, 4) / 2)

Key points

  • Decimal: a number type that stores money exactly, digit by digit
  • Use Decimal("0.1") to build an exact tenth from text
  • Floats store near guesses, so 0.1 + 0.2 misses 0.3
  • Fraction: a number type that stores an exact part, like one half
  • Use Fraction(a, b) to build an exact part from two whole numbers
  • Fractions stay exact through adding
  • A half plus a third is five sixths

In this example, the prices are Decimals built from text. A loop adds each price to a running total. The total prints as 4.00, with no stray digits. The last line halves three quarters of a cup, and Fraction gives 3/8.

Note

Build a Decimal from text, not from a float, because Decimal(0.1) keeps the float error.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does a shop total use Decimal instead of float?