Python Decimal
decimal is a module providing utilities and APIs for working with fixed point and floating point numbers.
Contents
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')
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