On this page
decimal
Prev: dbm | Up: stdlib_module | Next: difflib
Rel: numbers, math, cmath, fractions, random
Ref: docs.python.org — decimal
Tags: #public #python3 #stdlib
Import
import decimal
Overview
Exact base-10 fixed-point and floating-point arithmetic (Decimal, localcontext, rounding modes). Always use Decimal—never binary float—for money, prices, tax rates, accounting, and any calculation where 0.1 + 0.2 == 0.3 must hold exactly.
Quick Start
from decimal import Decimal
price = Decimal("19.99")
tax_rate = Decimal("0.0825")
total = (price * (1 + tax_rate)).quantize(Decimal("0.01"))
assert Decimal("0.1") + Decimal("0.2") == Decimal("0.3")
assert total == Decimal("21.64")
Implementation Walkthrough
1. Explicit Rounding & Currency Formatting (quantize + ROUND_HALF_UP)
Default rounding is ROUND_HALF_EVEN (banker's rounding). Specify an explicit rounding mode when business rules require half-up:
from decimal import Decimal, ROUND_HALF_UP
CENTS = Decimal("0.01")
def to_cents(amount: Decimal) -> Decimal:
return amount.quantize(CENTS, rounding=ROUND_HALF_UP)
assert to_cents(Decimal("2.345")) == Decimal("2.35")
2. Scoped Precision & Trap Changes with localcontext()
Never mutate global getcontext() in libraries—scope precision changes cleanly with localcontext():
from decimal import Decimal, localcontext
with localcontext() as ctx:
ctx.prec = 6
ratio = Decimal("1") / Decimal("7")
assert str(ratio) == "0.142857"
Gotchas & Boundaries
- Always construct from strings, never floats:
Decimal(0.1)captures the binary float error (0.10000000000000000555...); writeDecimal("0.1"). - Don't mix
Decimalandfloatin arithmetic:Decimal("1.0") + 0.5raisesTypeError; convert explicitly first. Decimalis slower thanfloat: Use it for financial/exact base-10 math, not large scientific matrix loops.- Enable
InvalidOperation/DivisionByZerotraps or check.is_finite()when accepting user-supplied numeric strings (sinceDecimal("NaN")andDecimal("Infinity")parse without error).
Common Functions
- decimal.getcontext() —
getcontext()— Get the current default context. - decimal.IEEEContext() —
IEEEContext(bits, /)— Return a context object initialized to the proper values for one of the IEEE interchange formats. The argument must be a multiple of 32 and less than IEEE_CONTEXT_MAX_BITS. - decimal.localcontext() —
localcontext(ctx=None, **kwargs)— Return a context manager that will set the default context to a copy of ctx on entry to the with-statement and restore the previous default context when exiting the with-statement. If no context is specified, a copy of the current - decimal.setcontext() —
setcontext(context, /)— Set a new default context.
Classes & Objects
- decimal.Clamped —
decimal.Clampedclass. (Methods:.add_note(),.with_traceback()) - decimal.Context — The context affects almost all operations and controls rounding, Over/Underflow, raising of exceptions and much more. A new context can be constructed as follows: (Methods:
.Etiny(),.Etop(),.abs(),.add(),.canonical(),.clear_flags()) - decimal.ConversionSyntax —
decimal.ConversionSyntaxclass. (Methods:.add_note(),.with_traceback()) - decimal.Decimal — Construct a new Decimal object. 'value' can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal('0'). The context does not affect the conversion and is only passed to determine if (Methods:
.adjusted(),.as_integer_ratio(),.as_tuple(),.canonical(),.compare(),.compare_signal()) - decimal.DecimalException —
decimal.DecimalExceptionclass. (Methods:.add_note(),.with_traceback()) - decimal.DecimalTuple — DecimalTuple(sign, digits, exponent) (Methods:
.count(),.index()) - decimal.DivisionByZero —
decimal.DivisionByZeroclass. (Methods:.add_note(),.with_traceback()) - decimal.DivisionImpossible —
decimal.DivisionImpossibleclass. (Methods:.add_note(),.with_traceback()) - decimal.DivisionUndefined —
decimal.DivisionUndefinedclass. (Methods:.add_note(),.with_traceback()) - decimal.FloatOperation —
decimal.FloatOperationclass. (Methods:.add_note(),.with_traceback()) - decimal.Inexact —
decimal.Inexactclass. (Methods:.add_note(),.with_traceback()) - decimal.InvalidContext —
decimal.InvalidContextclass. (Methods:.add_note(),.with_traceback()) - decimal.InvalidOperation —
decimal.InvalidOperationclass. (Methods:.add_note(),.with_traceback()) - decimal.Overflow —
decimal.Overflowclass. (Methods:.add_note(),.with_traceback()) - decimal.Rounded —
decimal.Roundedclass. (Methods:.add_note(),.with_traceback()) - decimal.Subnormal —
decimal.Subnormalclass. (Methods:.add_note(),.with_traceback()) - decimal.Underflow —
decimal.Underflowclass. (Methods:.add_note(),.with_traceback())
Constants & Attributes
decimal.BasicContext(Context) =Context(prec=9, rounding=ROUND_HALF_UP, Emin=-999999, Ema...decimal.DefaultContext(Context) =Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, ...decimal.ExtendedContext(Context) =Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, E...decimal.HAVE_CONTEXTVAR(bool) =Truedecimal.HAVE_THREADS(bool) =Truedecimal.IEEE_CONTEXT_MAX_BITS(int) =512decimal.MAX_EMAX(int) =999999999999999999decimal.MAX_PREC(int) =999999999999999999decimal.MIN_EMIN(int) =-999999999999999999decimal.MIN_ETINY(int) =-1999999999999999997decimal.ROUND_05UP(str) ='ROUND_05UP'decimal.ROUND_CEILING(str) ='ROUND_CEILING'decimal.ROUND_DOWN(str) ='ROUND_DOWN'decimal.ROUND_FLOOR(str) ='ROUND_FLOOR'decimal.ROUND_HALF_DOWN(str) ='ROUND_HALF_DOWN'
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/cmath
- tuts/python3/stdlib_module/dbm
- tuts/python3/stdlib_module/difflib
- tuts/python3/stdlib_module/fractions
- tuts/python3/stdlib_module/math
- tuts/python3/stdlib_module/numbers
- tuts/python3/stdlib_module/random
- tuts/python3/stdlib_module/statistics
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/core_fundamentals/primitive_data_types
Related notes
- tuts/python3/stdlib_module/cmath Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dbm Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/fractions Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/math Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/numbers Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/random Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/decimal/Clamped Linked here; shared tags: #stdlib