Python Glossary Русский

all Python 3Numbers & mathfunction

decimal.getcontext()

decimal

Return the current thread's Decimal context; its prec and rounding fields can be mutated in place and affect every subsequent operation.

Syntax

decimal.getcontext()
decimal.getcontext().prec = 50

prec counts significant digits of a result, not digits after the point, and the context does not touch the constructor: Decimal('1.23456789') keeps every digit, and rounding only happens once you do arithmetic. The context is per-thread, so a freshly started thread sees the defaults again; and when you need a different precision for just a few operations, a with decimal.localcontext() block beats poking the global context and forgetting to restore it.

Examples

import decimal
ctx = decimal.getcontext()
ctx.prec # → 28 (по умолчанию)
ctx.prec = 5
decimal.Decimal(1) / decimal.Decimal(7) # → Decimal('0.14286')
decimal.getcontext().rounding = decimal.ROUND_HALF_UP

See also

Open in the full glossarydocs.python.orgReport an inaccuracy