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.
from decimal import Decimal print(Decimal("0.1") + Decimal("0.2"))
Try it
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.
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)is0.1000000000000000055511151231257827.... UseDecimal(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.5raisesTypeError. 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 usequantize(). - Rounding.
quantize()andround()use banker's rounding by default (half goes to the even digit), which can surprise people used to "round half up". Passrounding=ROUND_HALF_UPwhere regulations or customers expect it.round(d)returns anint, whileround(d, 2)returns aDecimal. - Trailing zeros are kept.
Decimal("1.10")shows two places and equalsDecimal("1.1").normalize()strips zeros but may switch to scientific notation (Decimal("100").normalize()is1E+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
Decimalis still much slower thanfloat. Use it where exactness matters, not for scientific number crunching. - Storing and sending. JSON has no decimal type; pass
str(value)or usejson.loads(..., parse_float=Decimal). Databases generally map toNUMERICorDECIMALcolumns; 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.
Related
fractions,math,round(),float(),int()- Lessons: Numbers, Math and random, String formatting