Decimal Context Controls Precision And Rounding

Drive Decimal precision and rounding explicitly with getcontext and localcontext, and quantize amounts without binary floating point drift.

PythonData Integrity

Code

pythonsnippet
28 lines
from decimal import ROUND_DOWN, ROUND_HALF_UP, Decimal, getcontext, localcontext


def main() -> None:
    getcontext().prec = 6
    print('global precision:', getcontext().prec)
    print('1/3 at prec 6:', Decimal(1) / Decimal(3))

    # localcontext:局部改精度,不影响外部
    with localcontext() as ctx:
        ctx.prec = 10
        print('1/3 at prec 10:', Decimal(1) / Decimal(3))
    print('after block:', Decimal(1) / Decimal(3))

    # quantize:固定小数位 + 显式舍入模式
    amount = Decimal('2.675')
    for mode in (ROUND_HALF_UP, ROUND_DOWN):
        print(mode, amount.quantize(Decimal('0.01'), rounding=mode))

    # 默认是银行家舍入 ROUND_HALF_EVEN
    print('default:', Decimal('2.5').quantize(Decimal('1')))

    # 用字符串构造避免二进制浮点误差;一元 + 让上下文生效
    print('from float:', +Decimal(0.1), '| from str:', +Decimal('0.1'))


if __name__ == '__main__':
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

global precision: 6
1/3 at prec 6: 0.333333
1/3 at prec 10: 0.3333333333
after block: 0.333333
ROUND_HALF_UP 2.68
ROUND_DOWN 2.67
default: 2
from float: 0.100000 | from str: 0.1

What the code does

Decimal Context Controls Precision And Rounding is built around the function main.

The file repeats itself only inside for mode in (ROUND_HALF_UP, ROUND_DOWN). Everything borrowed from decimal is visible in one line: ROUND_DOWN, ROUND_HALF_UP, Decimal, getcontext, localcontext.

What to watch for

  • Plan for an install step: decimal is a real dependency, resolved by the package manager.

Applying it

The main signature reads def main() -> None

Look for the global precision:, 1/3 at prec 6:, 1/3 at prec 10: prefixes when the file runs; they tie each line to its step.

Statements that matter

with localcontext() as ctx:
    ctx.prec = 10
    print('1/3 at prec 10:', Decimal(1) / Decimal(3))

Interactive Tools for This Topic

FAQ

What does Decimal Context Controls Precision And Rounding print when run?
No setup needed: run the file and look for labeled lines like `global precision:`, `1/3 at prec 6:`, `1/3 at prec 10:` in the output.