Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 149 ยท Modules and the Standard Library

decimal and fractions

Avoid floating-point surprises in Python. Use Decimal for money, control precision and rounding with contexts, and Fraction for exact rational numbers.

Try 0.1 + 0.2 in Python and you get 0.30000000000000004. That isn't a Python bug. Ordinary float numbers are stored in binary, and most decimal fractions such as 0.1 have no exact binary form, just like 1/3 has no exact decimal form. For graphics, physics and most science, the tiny error is irrelevant. For money, tax or any rule that says "exactly two decimal places", it's a problem.

Python's standard library solves this with two modules. decimal gives you decimal arithmetic that behaves the way people expect, with precision and rounding you control. fractions gives you exact rational numbers such as 1/3. You'll learn when to use each, how rounding modes work and what the pitfalls are. If you need a refresher on regular numbers first, see Numbers and Math and Random.

Why floats surprise us

Python Float rounding error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second line prints False, and ten additions of 0.1 do not reach exactly 1.0. The value Python stores for 0.1 is the closest binary number, which is slightly more than 0.1.

Decimal basics

Create a Decimal from a string (or an integer) so you capture exactly the digits you meant:

Python Decimal arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Warning: Decimal(0.1) takes the float 0.1 and converts its exact binary value, giving 0.1000000000000000055511151231257827.... Always write Decimal("0.1") with quotes. If your data comes from a float, use Decimal(str(value)) or round first.

A Decimal mixes freely with integers, but not with floats. Decimal("1.5") + 1.5 raises TypeError, which protects you from accidentally bringing float errors back in.

Precision and the context

Division, square roots and similar operations can produce endless digits. The context controls how many significant digits are kept (28 by default) and which rounding rule applies:

Python Precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

localcontext() changes settings only inside the with block. Changing getcontext() directly affects the rest of the current thread, so prefer the with form in libraries.

flowchart LR
    A["Exact result<br/>of an operation"] --> B["Context precision<br/>(significant digits)"]
    B --> C["Rounding mode<br/>(ROUND_HALF_EVEN, ...)"]
    C --> D["Decimal result"]

Every arithmetic operation is rounded to the context's precision using its rounding mode.

Rounding to cents

For money you usually want a fixed number of decimal places, not significant digits. Use quantize() with a template that has the exponent you want:

Python quantize and rounding modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The default rule, ROUND_HALF_EVEN, rounds exact ties to the nearest even digit (so 0.5 becomes 0 and 1.5 becomes 2). This "banker's rounding" avoids a systematic upward bias when you add up many rounded values. Many shops and tax rules expect ROUND_HALF_UP ("school rounding"), so choose the mode your requirements specify and apply it in one place.

A small invoice example

Python Invoice with tax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Decimals work with f-strings and format() like other numbers, and str(Decimal) never uses scientific notation unless the exponent gets very large. When you store money in a database, use a decimal column type, or store integer cents.

Fractions

fractions.Fraction stores a numerator and denominator as integers, so results are exact and always reduced to lowest terms:

Python Fraction basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice Fraction(0.1) prints 3602879701896397/36028797018963968: that is precisely what the float 0.1 stores. To get the intended one tenth, pass a string, or use Fraction(0.1).limit_denominator(1000), which finds the closest simple fraction:

Python limit_denominator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Fractions mix with integers and other fractions exactly. Combined with a float, the result becomes a float. Because fractions can grow big, they suit teaching, symbolic-style work and exact checks, not heavy numeric computing, where NumPy is better.

Choosing the right number type

Need Use
Speed, science, graphics float
Money, rules about decimal places Decimal
Exact ratios such as 1/3 Fraction
Whole numbers of any size int

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line creates the exact decimal value 0.1?

    Creating from a string keeps exactly the digits you wrote. Decimal(0.1) copies the float's binary approximation.
  2. 2. What does Decimal('2.675').quantize(Decimal('0.01')) give with the default context?

    The default mode is ROUND_HALF_EVEN. 2.675 is an exact tie, and rounding to the even neighbor means 2.68 (8 is even). Because Decimal is exact, there is no hidden float error.
  3. 3. What happens with Decimal('1.5') + 1.5?

    Decimal refuses to mix with floats so float errors can't sneak in silently. Convert the float explicitly first.
  4. 4. What is Fraction(6, 8)?

    Fractions are always stored in lowest terms, so 6/8 becomes 3/4.

Summary

  • Binary floats can't represent most decimal fractions exactly, which causes errors like 0.1 + 0.2 != 0.3.
  • Decimal does exact decimal arithmetic. Build values from strings, not floats.
  • The context sets precision (default 28 digits) and rounding; use localcontext() to change it temporarily.
  • Use quantize() with a rounding mode to round money to cents, and apply the rule your business requires.
  • Fraction keeps exact rational numbers in lowest terms; limit_denominator() finds simple approximations.

Next: The statistics Module, where you'll summarize data sets with a few function calls.