Python - Numeric Decimal precision


With decimal module you can set the precision of all decimal numbers, arrange error handling, and more.

You can use context object to set precision (number of decimal digits) and round modes (down, ceiling, etc.).

The precision is applied globally for all decimals created in the calling thread:


import decimal 
from decimal import Decimal 
print( decimal.Decimal(1) / decimal.Decimal(7) )                     # Default: 28 digits 
# from ww  w  .  java 2 s  .  c o m
decimal.getcontext().prec = 4                               # Fixed precision 
print( decimal.Decimal(1) / decimal.Decimal(7) ) 

print( Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3) )   # Closer to 0


This is useful for monetary applications, where cents are represented as two decimal digits.

Decimals are an alternative to manual rounding and string formatting in this context:


import decimal 

print( 1999 + 1.33 )      # This has more digits in memory than displayed in 3.3 
decimal.getcontext().prec = 2 # from  w  w w. j  a  va2 s .co m
pay = decimal.Decimal(str(1999 + 1.33)) 
print( pay )


Related Topic