On this page
  1. decimal
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Explicit Rounding & Currency Formatting (quantize + ROUND_HALF_UP)
  7. 2. Scoped Precision & Trap Changes with localcontext()
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes