Python - Numeric Decimal precision

Introduction

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:

Demo

import decimal 
from decimal import Decimal 
print( decimal.Decimal(1) / decimal.Decimal(7) )                     # Default: 28 digits 
# www.  j av a  2  s . co  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

Result

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:

Demo

import decimal 

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

Result

Related Topic