decimal.Decimal() vs decimal.getcontext()
decimal.Decimal() and decimal.getcontext() are both Python Decimal Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. decimal.Decimal(): Creates a Decimal number from a string, integer, or float. Provides exact decimal arithmetic. Its syntax is decimal.Decimal(value="0", context=None), and it returns decimal object decimal.getcontext(): Returns the current thread-local Decimal context (precision, rounding, traps). Its syntax is decimal.getcontext(), and it returns context object Example of decimal.Decimal(): from decimal import Decimal
Decimal("0.1") + Decimal("0.2") # Decimal("0.3") (exact!)
0.1 + 0.2 # 0.30000000000000004 (float: not exact). Example of decimal.getcontext(): ctx = decimal.getcontext()
ctx.prec = 50 # Set 50 significant digits
ctx.rounding = decimal.ROUND_HALF_UP. Read the full references for decimal.Decimal() and decimal.getcontext() to see parameters, edge cases, and example code side by side. Other Decimal Module APIs worth comparing: decimal.localcontext(), decimal.Decimal.quantize().