decimal — decimal fixed-point and floating-point arithmetic

Decimal construction from strings versus floats, localcontext precision, and quantize rounding, checked on Python 3.13.12.

模块页正文目前为英文。

The decimal module implements correctly rounded decimal arithmetic. The default context uses precision 28 and rounding ROUND_HALF_EVEN. Examples were checked on Python 3.13.12 and do not change the process-wide context except inside localcontext.

Construct Decimal from a string or an int when the decimal digits matter. Decimal(0.1) stores the binary floating-point value of 0.1, which is not exactly one tenth. This page does not reteach the math module.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Construction from strings and floats

Decimal(value='0', context=None) accepts a string, int, Decimal, or float, among other documented forms. print uses the decimal string; Decimal("0.1") prints as 0.1, while Decimal(0.1) prints the longer exact binary value. Those two values are not equal.

Mixing Decimal and float in arithmetic, such as Decimal(1) + 0.1, raises TypeError. An invalid numeric string raises InvalidOperation when that signal is trapped, which is the default. InvalidOperation is a DecimalException and a subclass of ArithmeticError, not of ValueError.

decimal.Decimal

class decimal.Decimal(value='0', context=None)

Create a Decimal from a string or int for exact decimal digits, or from a float for the exact binary value.

ParameterDescription
valueA string, int, Decimal, or float, or another documented input. Use a string such as '0.1' when you want the decimal tenth.
contextOptional context used for conversion. The default context applies when this is omitted.

Returns: A Decimal instance. print uses __str__, which is the coefficient and exponent, not the Decimal(...) constructor form.

Raises

  • TypeError — Raised by arithmetic that mixes Decimal and float, such as Decimal(1) + 0.1 on Python 3.13.12.
  • InvalidOperation — Raised for an invalid string such as 'nope' when the InvalidOperation trap is enabled. It is a subclass of ArithmeticError.
python
from decimal import Decimal, InvalidOperation

print(Decimal("0.1"))
print(Decimal(0.1))
print(Decimal(0.1) == Decimal("0.1"))
print(Decimal(1) + Decimal("0.1"))
try:
    Decimal(1) + 0.1
except TypeError as err:
    print(type(err).__name__)
try:
    Decimal("nope")
except InvalidOperation as err:
    print(type(err).__name__)

Expected output

0.1
0.1000000000000000055511151231257827021181583404541015625
False
1.1
TypeError
InvalidOperation

Related: fractions

Official documentation →

localcontext precision and quantize

decimal.localcontext(ctx=None, **kwargs) is a context manager that copies the current context, or ctx if given. Changes made inside the with block do not persist after it exits. Since Python 3.11, keyword arguments such as prec=4 set attributes on that copy. The examples use localcontext rather than assigning getcontext().prec, so the default precision 28 is left in place.

Decimal.quantize(exp, rounding=None, context=None) returns a value with the exponent of exp after rounding. With the default ROUND_HALF_EVEN, 1.25 quantized to tenths is 1.2 and 1.35 is 1.4; 2.5 and 3.5 quantized to ones become 2 and 4. Passing rounding= overrides the context for that call only.

decimal.localcontext, Decimal.quantize

decimal.localcontext(ctx=None, **kwargs)
Decimal.quantize(exp, rounding=None, context=None)

Temporarily change precision, then round a Decimal to a given exponent.

ParameterDescription
ctx / kwargslocalcontext copies ctx, or the current context if ctx is None. Keyword arguments such as prec set attributes on the copy (added in Python 3.11).
exp / roundingquantize uses the exponent of exp. rounding is a rounding mode such as ROUND_HALF_UP; the context rounding is used when this is omitted.

Returns: The with block yields a Context. Division and quantize return Decimal values.

  • The first and third lines of output are the default-context value of Decimal('1') / Decimal('7') at precision 28.
  • ROUND_HALF_EVEN is the default rounding mode. ROUND_DOWN is toward zero, not toward negative infinity; that is ROUND_FLOOR.
python
from decimal import Decimal, localcontext, ROUND_HALF_UP, ROUND_DOWN

print(Decimal("1") / Decimal("7"))
with localcontext() as ctx:
    ctx.prec = 3
    print(Decimal("1") / Decimal("7"))
print(Decimal("1") / Decimal("7"))
with localcontext(prec=4):
    print(Decimal("1") / Decimal("3"))
print(Decimal("1.25").quantize(Decimal("0.1")))
print(Decimal("1.35").quantize(Decimal("0.1")))
print(Decimal("1.25").quantize(Decimal("0.1"), rounding=ROUND_HALF_UP))
print(Decimal("1.25").quantize(Decimal("0.1"), rounding=ROUND_DOWN))
print(Decimal("2.5").quantize(Decimal("1")), Decimal("3.5").quantize(Decimal("1")))

Expected output

0.1428571428571428571428571429
0.143
0.1428571428571428571428571429
0.3333
1.2
1.4
1.3
1.2
2 4

Official documentation →