Python Decimal
decimal is a module providing utilities and APIs for working with fixed point and floating point numbers.
Usage
Decimal
A decimal.Decimal object can be instantiated with any of the following methods.
import decimal decimal.Decimal('3.14') #Decimal('3.14') decimal.Decimal(3.14) #Decimal('3.140000000000000124344978758017532527446746826171875') decimal.Decimal((0, (3, 1, 4), -2)) #Decimal('3.14')
As demonstrated above, instantiating a decimal.Decimal object with a float is not likely to produce the desired result. When possible, construct numbers from strings. If an irrational number can be expressed as a fraction, compute it from decimal.Decimal objects.
d1 = decimal.Decimal(10) d2 = decimal.Decimal(3) d1 / d2 #Decimal('3.3333333333333333333333333333')
There are also special values that can be instantiated like:
decimal.Decimal('Infinity')
decimal.Decimal('-Infinity')
decimal.Decimal('NaN')
decimal.Decimal('-0')
Contexts
Implicitly, decimal.Decimal objects inherit a set of behavior configurations from the active thread's context.
To examine or overwrite the active thread's context, use decimal.getcontext and decimal.setcontext. The object returned by decimal.getcontext is also directly writeable.
import decimal decimal.getcontext() #Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero, InvalidOperation]) getcontext().prec += 2
It is also possible to use a local context manager.
import decimal with decimal.localcontext() as ctx: ctx.prec = 42 d = decimal.Decimal(10) / decimal.Decimal(3) # The unary `+` operator rounds `d` to the active thread's precision +d
Constants
Constant |
Meaning |
decimal.ROUND_CEILING |
Round towards Infinity |
decimal.ROUND_DOWN |
Round towards zero |
decimal.ROUND_FLOOR |
Round towards -Infinity |
decimal.ROUND_HALF_DOWN |
Round to nearest with ties going towards zero |
decimal.ROUND_HALF_EVEN |
Round to nearest with ties going to nearest even integer |
decimal.ROUND_HALF_UP |
Round to nearest with ties going away from zero |
decimal.ROUND_UP |
Round away from zero |
decimal.ROUND_05UP |
Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero |
See also
Python decimal module documentation
Python Module of the Day article for decimal