Python

Python decimal — Decimal, quantize, rounding, and money

Money, prices, and rates are stated in decimal places, and the float type does not hold most of them exactly: 0.1 + 0.2 comes back as 0.30000000000000004. The decimal module holds a number the way it was written, adds and multiplies it exactly within a stated precision, and rounds it to the number of places the job states, under the rounding rule the job picks. This guide takes construction first, then precision, quantize, the rounding modes, a priced example, and the error cases.

Written November 13, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: float against Decimal
  • Construction: strings, integers, and tuples
  • Precision: the context and its 28 digits
  • Quantize: round to a stated number of places

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

The decimal module gives a number type, Decimal, that stores a value in base 10. A float stores a value in base 2, and most decimal fractions have no exact base 2 form, so the float nearest to 0.1 is a little above 0.1 and the float nearest to 0.2 is a little above 0.2. Added together, the pair lands a little above 0.3 and prints with the error showing. A Decimal built from the string "0.1" is exactly one tenth, and the same sum is exactly three tenths. The module also states its working rules in a context: a precision, which caps the number of significant digits in a result, and a rounding mode, which decides what happens to the digits that fall off. Code that prices, taxes, bills, or splits money uses this module for those two rules as much as for the exact storage.

The main program: float against Decimal

The first two lines run the float sum. The next two lines run the same sum with Decimal values built from strings. The last line builds a Decimal from the float 0.1 itself, and it shows what that float really holds:

Python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print(Decimal(0.1))

The exact output:

Output
0.30000000000000004
False
0.3
True
0.1000000000000000055511151231257827021181583404541015625

The last line is the rule that shapes the whole module: build a Decimal from a string or an integer, never from a float. A float passed in is converted exactly, and exact conversion of a float that was never exact carries its full error into the new value, where it stays visible. The string form states the value the writer meant, and the module holds that value.

Construction: strings, integers, and tuples

A Decimal can be built from an integer, from a string, and from a tuple of a sign, a tuple of digits, and an exponent. A string in exponent form is accepted and kept in that form. An integer can be added to a Decimal and the result is a Decimal. A float cannot be added, and the attempt raises TypeError:

Python
from decimal import Decimal
print(Decimal(7))
print(Decimal("3.14"))
print(Decimal((0, (1, 4, 1, 5, 9), -4)))
print(Decimal("1e3"))
print(Decimal(7) + 1)
try:
    print(Decimal("1.5") + 0.5)
except TypeError as e:
    print(type(e).__name__)

The exact output:

Output
7
3.14
1.4159
1E+3
8
TypeError

The tuple form reads as the sign 0 (positive), the digits 14159, and the exponent -4, which places the point four digits from the right and gives 1.4159. That form is rarely typed by hand; it is the form the type itself uses to state a value in parts, and it appears when a value is taken apart and rebuilt. The TypeError on the mixed sum is deliberate. Mixing a float into decimal arithmetic would import the float error the module exists to keep out, so the module refuses the operation instead of guessing at a conversion.

Precision: the context and its 28 digits

The context holds the precision: the maximum number of significant digits a result may carry. The default is 28. Division is the operation where precision shows, because a quotient such as one third has no end. At the default precision the result carries 28 digits. Lower the precision to 6 and the same division carries 6 digits, rounded at the last one. Restore 28 and the full result returns:

Python
from decimal import Decimal, getcontext
print(getcontext().prec)
print(Decimal(1) / Decimal(3))
getcontext().prec = 6
print(Decimal(1) / Decimal(3))
print(Decimal(2) / Decimal(3))
getcontext().prec = 28
print(Decimal(1) / Decimal(3))

The exact output:

Output
28
0.3333333333333333333333333333
0.333333
0.666667
0.3333333333333333333333333333

Two thirds at precision 6 prints 0.666667, not 0.666666: the seventh digit is a 6, so the sixth digit rounds up. Precision is a property of the context, not of a single value, and changing it with getcontext changes it for every decimal operation that follows in that thread. The scoped form, localcontext, appears in the last section; it is the form to use when only one block of work needs a different precision.

Quantize: round to a stated number of places

The quantize call rounds a value to the places stated by its argument. The argument is itself a Decimal, and its exponent states the places: Decimal("0.01") states two places, Decimal("1") states whole units. The result carries exactly those places, with trailing zeros kept:

Python
from decimal import Decimal
cents = Decimal("0.01")
print(Decimal("2.675").quantize(cents))
print(Decimal("1.005").quantize(cents))
print(Decimal("19.99").quantize(cents))
print(Decimal("19.9").quantize(cents))
print(Decimal("1234567.891").quantize(Decimal("1")))

The exact output:

Output
2.68
1.00
19.99
19.90
1234568

The first two lines are a pair worth reading slowly. 2.675 rounds to 2.68, and 1.005 rounds to 1.00. Both sit exactly halfway between two results, and the default rounding mode, half even, sends a halfway value to the neighbor whose last kept digit is even. For 2.675 the even neighbor is 2.68 (8 is even); for 1.005 it is 1.00 (0 is even). The fourth line shows the trailing zero kept: 19.9 stated to two places is 19.90, and that zero is part of the value a price carries. Because these inputs were built from strings, the halfway cases are true halfway cases; a float input would sit a hair to one side and round on that hair.

Rounding modes: half even, half up, down, floor, ceiling

The rounding argument of quantize picks the rule. Five modes cover most work. Half even is the default already seen. Half up sends a halfway value away from zero. Down cuts the extra digits off, toward zero. Floor rounds toward the lower value and ceiling toward the higher one, and the two part company on negative numbers:

Python
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_DOWN, ROUND_FLOOR, ROUND_CEILING
whole = Decimal("1")
for mode in [ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_DOWN, ROUND_FLOOR, ROUND_CEILING]:
    print(mode, Decimal("2.5").quantize(whole, rounding=mode), Decimal("-2.5").quantize(whole, rounding=mode))

The exact output:

Output
ROUND_HALF_EVEN 2 -2
ROUND_HALF_UP 3 -3
ROUND_DOWN 2 -2
ROUND_FLOOR 2 -3
ROUND_CEILING 3 -2

Read the negative column by itself. Down and half even both give -2 for -2.5, floor gives -3 because -3 is the lower value, and ceiling gives -2 because -2 is the higher one. A rule stated as "round down" is ambiguous until the mode is named: one reader means toward zero, another means toward the floor, and on a negative value the two differ by a full unit. Name the mode in the code, and the code states the rule with no reading needed. Prices that a customer sees are most often stated with half up, because that is the rule people expect from school arithmetic; totals kept for later sums are often left at half even, which sends halfway values up and down in balance across many roundings.

A priced example: tax, total, and a split

A priced job puts the pieces together. Multiply a price by a count and the product is exact. Multiply by a tax rate and the product runs past two places, so it is quantized to cents at the step where the amount becomes an amount owed. Add, and the total is exact. Split the total three ways and the split is quantized to cents as well:

Python
from decimal import Decimal
cents = Decimal("0.01")
subtotal = Decimal("19.99") * 3
tax = (subtotal * Decimal("0.08")).quantize(cents)
total = subtotal + tax
print(subtotal)
print(tax)
print(total)
print((total / 3).quantize(cents))
print((Decimal("100.00") / 3).quantize(cents))

The exact output:

Output
59.97
4.80
64.77
21.59
33.33

The tax on 59.97 at 8 percent is 4.7976 before rounding, and the quantize step makes it 4.80, the amount that can actually be charged. The split lines show the limit of any cent-based split: 64.77 divides by 3 exactly, so each share is 21.59, while 100.00 divided by 3 gives 33.33 per share and three shares come to 99.99. The missing cent is not an error in the module; it is a fact of splitting a two-place total into equal two-place parts, and code that splits a bill has to place that cent somewhere on purpose.

Errors, and a scoped precision with localcontext

Three error cases close the guide. A string that is not a number raises InvalidOperation when the Decimal is built. A division by zero raises DivisionByZero. A square root of a negative value raises InvalidOperation. Below them, localcontext sets a precision that holds only inside its block; the division outside the block runs at the full default precision again:

Python
from decimal import Decimal, InvalidOperation, DivisionByZero, localcontext
try:
    Decimal("abc")
except InvalidOperation as e:
    print(type(e).__name__)
try:
    Decimal(1) / Decimal(0)
except DivisionByZero as e:
    print(type(e).__name__)
try:
    Decimal("-1").sqrt()
except InvalidOperation as e:
    print(type(e).__name__)
with localcontext() as ctx:
    ctx.prec = 4
    print(Decimal(10) / Decimal(3))
print(Decimal(10) / Decimal(3))

The exact output:

Output
InvalidOperation
DivisionByZero
InvalidOperation
3.333
3.333333333333333333333333333

The errors are stated as exceptions a program can catch by name, so input read from a file or a form can be checked at the build step and reported as bad input. Division by zero in this module raises rather than returning an infinity value, which suits priced work: a rate divided by a zero count is a defect to surface, not a number to carry forward. The localcontext block is the safe way to borrow a different precision. It copies the current context, applies the change inside the block, and restores the original on exit, so no later code inherits a precision it did not ask for.

Which choice for which job

Job Choice Why
Build from written value Decimal from string Holds value as written
Build from whole number Decimal from int Exact, no float error
Round to cents quantize States places exactly
Customer-facing rounding ROUND_HALF_UP Half away from zero
Balanced repeated rounding ROUND_HALF_EVEN Half to even neighbor
Short-lived precision change localcontext Restores on exit
Add a rate or price Decimal operands Float operand refused
Split a total quantize the share Cent placed on purpose

Checklist

  • Build Decimal values from strings or integers; never build one from a float that carries a value you care about.
  • Quantize at the step where an amount becomes an amount owed, and state the places with the argument.
  • Name the rounding mode wherever the rule matters; half even is the default and may not be the rule the job states.
  • Leave the context precision at its default unless a block needs otherwise, and make that change with localcontext.
  • Catch InvalidOperation where Decimal values are built from outside input.
  • When a total is split, decide where the leftover cent goes instead of letting it vanish.

Sources

  • Python Standard Library, decimal — Decimal construction from strings, integers, floats, and tuples, the context and its default precision of 28, quantize and the rounding modes, localcontext and getcontext, and the InvalidOperation and DivisionByZero signals.

Keep Exploring