Python - Decimal and Fraction numbers

Introduction

Decimal numbers are fixed-precision floating-point numbers.

Fraction numbers are rational numbers with both a numerator and a denominator.

Both can work around the limitations and inherent inaccuracies of floating-point math:

Demo

print( 1 / 3 )                           # Floating-point (add a .0 in Python 2.X) 
print( (2/3) + (1/2) )

import decimal                  # Decimals: fixed precision 
d = decimal.Decimal('3.141') 
print( d + 1 )# from w  w w.j a v  a 2 s. c o  m
decimal.getcontext().prec = 2 
print( decimal.Decimal('1.00') / decimal.Decimal('3.00') )

from fractions import Fraction  # Fractions: numerator+denominator 
f = Fraction(2, 3)

print( Fraction(5, 3) )
print( f + Fraction(1, 2) )

Result

Related Topic