Python Numbers and Math · Lesson 16 of 149

Python Decimal and Fractions

What you will learn

  • Why and when to use Decimal instead of float
  • How to create a Decimal correctly (from text, not from a float)
  • How to round to cents with quantize, and the rounding modes
  • What the precision setting does
  • How to use Fraction for exact ratios

Lesson 3.4 showed that floats are approximate. Python's standard library has two number types that are exact for the kinds of number they handle. They need an import (chapter 16 covers imports in full; for now just copy the import line).

1. Decimal: exact decimal arithmetic

Decimal stores numbers the way people write them: as decimal digits. So 0.1 really is 0.1.

from decimal import Decimal

print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
0.3
True

Compare with the float result 0.30000000000000004 from lesson 3.4. Use Decimal for money and anywhere the digits matter.

Quick check: why is `Decimal("0.1") + Decimal("0.2")` exactly `0.3`?

Decimal stores decimal digits, not a binary approximation, so 0.1 and 0.2 are stored exactly and the sum is exact.

Create a Decimal from text

This is the most important rule: make a Decimal from a string (or an int), not from a float. A float has already lost the exact value:

print(Decimal(0.1))
print(Decimal("0.1"))
print(Decimal(3))
0.1000000000000000055511151231257827021181583404541015625
0.1
3

Decimal(0.1) faithfully copies the float's hidden error. Decimal("0.1") is the number you meant.

Working with Decimals

The usual operators work, and the number of decimal places is kept:

print(Decimal("19.99") * 3)
print(Decimal("1.10") + Decimal("2.20"))
print(Decimal("1.10") * 2)
print(str(Decimal("3.50")))
59.97
3.30
2.20
3.50

Notice that 3.30 keeps its trailing zero. That is useful for money. You can mix a Decimal with an int, but not with a float:

Decimal("0.1") + 0.2
TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'

Python refuses on purpose, because mixing would bring the float error back in.

You can turn a Decimal into other types: float(Decimal("0.1")) is 0.1 and int(Decimal("3.9")) is 3 (cut, like any int()).

2. Rounding: quantize

To round to cents, use quantize with a pattern that shows the places you want:

from decimal import Decimal

price = Decimal("2.675")
print(price.quantize(Decimal("0.01")))
2.68

By default, Decimal rounds ties to the even neighbour, like round (lesson 3.3). 2.675 is an exact tie, and 8 is even, so the answer is 2.68. A tie like 2.665 goes to 2.66:

print(Decimal("2.665").quantize(Decimal("0.01")))
2.66

If you want the "5 rounds up" rule from school, give a rounding mode:

from decimal import Decimal, ROUND_HALF_UP

print(Decimal("2.665").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
2.67
Mode Rule
ROUND_HALF_EVEN (default) ties go to the even neighbour
ROUND_HALF_UP ties go up (away from zero)
ROUND_DOWN always cut towards zero

Which mode to use may be decided by a law or an accounting rule, so check the rules where you work.

3. Precision

Decimal calculations keep a limited number of significant digits, 28 by default:

from decimal import Decimal, getcontext

print(getcontext().prec)
print(Decimal(1) / Decimal(7))
28
0.1428571428571428571428571429

You can change the precision for a block of code with localcontext:

from decimal import Decimal, localcontext

with localcontext() as ctx:
    ctx.prec = 5
    print(Decimal(1) / Decimal(7))
0.14286

(with statements are covered in chapter 14.)

4. Fraction: exact ratios

Some numbers are not decimals at all, such as one third. The fractions module stores a number as a numerator and denominator, so it is exact:

from fractions import Fraction

print(Fraction(1, 3) + Fraction(1, 6))
print(Fraction(1, 3) * 3)
print(Fraction(6, 8))
print(Fraction("0.75"))
1/2
1
3/4
3/4
  • Fractions are reduced automatically: 6/8 becomes 3/4.
  • You can make one from text: Fraction("0.75") is 3/4.
  • Use .numerator and .denominator to read the parts.

As with Decimal, avoid creating from a float. Fraction(0.1) exposes the float's error, while Fraction("0.1") is 1/10:

print(Fraction(0.1))
print(Fraction("0.1"))
3602879701896397/36028797018963968
1/10

A fraction mixed with a float gives a float (Fraction(1, 3) + 0.5 is 0.8333333333333333), so keep to fractions and ints when you want exactness. Convert to a float at the very end with float(...).

To find a simple fraction close to a number, use limit_denominator:

print(Fraction(0.1).limit_denominator(100))
print(Fraction(3.14159).limit_denominator(100))
1/10
311/99

5. Which one to use?

Need Use
everyday maths, science, speed float (accept tiny errors, show with round)
money, exact decimal digits Decimal (create from text)
exact ratios such as 1/3 Fraction
very large exact whole numbers int

Decimal and Fraction are slower than float, but for ordinary programs the difference does not matter.

Worked example: a shop bill

Three items cost 19.99 each, and there is 8.25% tax. Find the total, rounded to cents.

from decimal import Decimal

subtotal = Decimal("19.99") * 3
tax = subtotal * Decimal("0.0825")
total = (subtotal + tax).quantize(Decimal("0.01"))
print(subtotal, tax, total)
59.97 4.947525 64.92
Step Calculation Result
1 19.99 * 3 59.97
2 59.97 * 0.0825 4.947525 (exact)
3 59.97 + 4.947525 64.917525
4 round to 2 places 64.92

The tax rate here is made up for the example. Every step is exact until the final rounding.

Common mistakes

  • Creating a Decimal from a float. Decimal(0.1) copies the error; use Decimal("0.1").
  • Mixing Decimal and float in one calculation, which raises TypeError.
  • Rounding too early. Keep full precision until the final quantize.
  • Forgetting that the default rounding of ties goes to even.
  • Using Decimal for everything. Plain floats are fine for most calculations.

Key takeaways

  • Decimal is exact for decimal digits; create it from text: Decimal("0.1").
  • It refuses to mix with floats, but works with ints.
  • Round with quantize(Decimal("0.01")); the default rounding sends ties to the even neighbour, and ROUND_HALF_UP gives the school rule.
  • Fraction(numerator, denominator) is exact and reduces itself; avoid building it from floats.
  • Use float for general maths, Decimal for money, Fraction for exact ratios.

Practice

1. What is the difference between Decimal(0.1) and Decimal("0.1")?

Show answer

Decimal(0.1) copies the float's stored error (0.1000000000000000055...). Decimal("0.1") is exactly 0.1.

2. What does Decimal("0.1") + 0.2 do, and why?

Show answer

It raises a TypeError. Python does not allow mixing Decimal and float, to keep the float error out.

3. Write the line that rounds Decimal("7.456") to 2 decimal places.

Show answer

Decimal("7.456").quantize(Decimal("0.01")), which gives 7.46.

4. What is Fraction(2, 6)?

Show answer

1/3. Fractions are reduced automatically.

5. What does Fraction(1, 2) + Fraction(1, 3) give?

Show answer

5/6.

6. For each, choose float, Decimal or Fraction: (a) the speed of a car in a simulation, (b) the price of a basket, (c) exactly one third of a pizza.

Show answer

(a) float, (b) Decimal, (c) Fraction.