Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Math, Data and Text

The decimal module

Reference for Python's decimal module: exact decimal numbers for money, precision and rounding contexts, quantize, ROUND_HALF_UP, and float pitfalls.

The decimal module provides the Decimal type, a number stored in base 10. Where a float approximates 0.1 in binary and gets it slightly wrong, a Decimal("0.1") is exactly one tenth. That makes Decimal the right choice for money, tax and any calculation where people expect the same answer as on paper.

A Decimal should be created from a string (or an integer). Creating one from a float copies the float's inexact binary value, digit for digit. Arithmetic follows a context that controls precision (28 significant digits by default) and rounding, which you can change globally or for a block of code.

Python
from decimal import Decimal

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

Try it

Python Exact sums and rounding

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.

Python Precision, contexts and pitfalls

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.

Frequently used names

Name Description
Decimal(value="0") Creates a decimal from a string, int, tuple or float. Invalid strings raise decimal.InvalidOperation.
quantize(exp, rounding=None) Rounds to the same number of decimal places as exp, for example Decimal("0.01"). The standard way to round money.
getcontext(), setcontext(ctx), localcontext() Read or replace the current context; localcontext() is a temporary override in a with block.
Context(prec, rounding, traps, ...) A set of arithmetic rules: precision, rounding mode, and which conditions raise exceptions.
Rounding modes ROUND_HALF_EVEN (default), ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_05UP.
sqrt(), ln(), log10(), exp(), fma(), copy_abs() and more Methods that compute with the context's precision.
as_tuple(), normalize(), is_nan(), is_finite() Inspect and tidy values.
Exceptions decimal.DecimalException and subclasses InvalidOperation, DivisionByZero, Inexact, Rounded, Overflow.

Usage notes

  • Build from strings. Decimal("0.1") is exact; Decimal(0.1) is 0.1000000000000000055511151231257827.... Use Decimal(str(x)) only if you know the float came from a short decimal.
  • Floats and decimals do not mix in arithmetic: Decimal("1.5") + 0.5 raises TypeError. They can be compared, though the result reflects the float's exact value. Ints mix freely.
  • Precision counts significant digits, not decimal places. The default context has 28 significant digits, so Decimal(1) / Decimal(3) has 28 threes. For a fixed number of places use quantize().
  • Rounding. quantize() and round() use banker's rounding by default (half goes to the even digit), which can surprise people used to "round half up". Pass rounding=ROUND_HALF_UP where regulations or customers expect it. round(d) returns an int, while round(d, 2) returns a Decimal.
  • Trailing zeros are kept. Decimal("1.10") shows two places and equals Decimal("1.1"). normalize() strips zeros but may switch to scientific notation (Decimal("100").normalize() is 1E+2).
  • The context is per thread, and localcontext() is the safe way to change it temporarily, including for async code.
  • Speed. The C implementation is fast, but Decimal is still much slower than float. Use it where exactness matters, not for scientific number crunching.
  • Storing and sending. JSON has no decimal type; pass str(value) or use json.loads(..., parse_float=Decimal). Databases generally map to NUMERIC or DECIMAL columns; SQLite has no exact decimal type and stores floats unless you keep integers (cents) or strings.
  • Alternative: integers. Many money systems store whole cents as int, which is fast and exact, and only format with a decimal point for display.