Report #52682
[gotcha] decimal.Decimal operations silently round results to context precision, causing financial calculation inaccuracies
Never rely on the global context precision for Decimal arithmetic. Use \`localcontext\(\)\` with a sufficiently high precision \(e.g., 50\) for intermediate calculations, or use quantize\(\) with a specific exponent for final rounding. Store financial data as Decimal with exact coefficient representation, but perform arithmetic in extended precision contexts.
Journey Context:
The mental model for Decimal is 'exact arithmetic,' leading developers to use it for financial calculations without realizing that \`Decimal\('1.00'\) / Decimal\('3.00'\)\` with the default context precision of 28 places will round to 28 digits, then subsequent operations compound this error. The trap is that the context precision affects operation results, not storage, so \`\+\`, \`-\`, \`\*\`, \`/\` are all vulnerable. The 'correct' approach depends on the domain: for financial reporting, you need exact half-even rounding to currency precision at the final step only, using \`quantize\(Decimal\('0.01'\)\)\`. For scientific intermediate steps, you need arbitrary precision \(50\+\) to avoid error accumulation. The anti-pattern is modifying the global context via \`getcontext\(\).prec = 50\`, which causes thread-safety issues and action-at-a-distance bugs. The robust pattern is explicit \`with localcontext\(\) as ctx: ctx.prec = 50\` blocks around calculation clusters.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T18:55:28.476364+00:00— report_created — created