Another context that is used frequently is the decimal context. This context defines a number of properties of the decimal.Decimal calculation, including the quantization rules used to round or truncate values.
We might see application programming that looks similar to the following code snippet:
import decimal PENNY = decimal.Decimal("0.00") price = decimal.Decimal('15.99') rate = decimal.Decimal('0.0075') print(f"Tax={(price * rate).quantize(PENNY)}, Fully={price * rate}") with decimal.localcontext() as ctx: ctx.rounding = decimal.ROUND_DOWN tax = (price*rate).quantize(PENNY) print(f"Tax={tax}")
The preceding example shows both a default context as well as a local context. The default context is shown first, and it uses the default rounding rule.
The localized context begins with the with decimal.localcontext() as ctx: statement. Within this context, the decimal rounding has been defined to round down for this particular calculation.
The with statement is used to assure that the original context is restored after the localized change. Outside this context, the default rounding applies. Inside this context, a modified rounding rule applies.