- Mastering Objectoriented Python
- Steven F. Lott
- 141字
- 2021-11-12 16:25:19
Using the decimal context
Another context that is used frequently is the decimal context. This context defines a number of properties of decimal.Decimal
calculation, including the quantization rules used to round or truncate values.
We might see application programming that looks like the following:
import decimal PENNY=decimal.Decimal("0.00") price= decimal.Decimal('15.99') rate= decimal.Decimal('0.0075') print( "Tax=", (price*rate).quantize(PENNY), "Fully=", price*rate ) with decimal.localcontext() as ctx: ctx.rounding= decimal.ROUND_DOWN tax= (price*rate).quantize(PENNY) print( "Tax=", tax )
The preceding example shows the default context as well as a local context. The default context has the default rounding rule. The localized context, however, shows how we can assure consistent operations by setting the decimal rounding for a 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 specific rounding applies.