Rounding logic in Python?
Question: In my original code I was trying to compute some indices out of some float
values and I faced the following problem:

    
    
    >>> print int((1.40-.3)/.05)
    21
    

But:

    
    
    >>> print ((1.40-.3)/.05)
    22.0
    

I am speechless about what is going on. Can somebody please explain?


Answer: This is caused by floating point inaccuracy:

    
    
    >>> print repr((1.40-.3)/.05)
    21.999999999999996
    

You could try using the `Decimal` type instead:

    
    
    >>> from decimal import Decimal
    >>> Decimal
    <class 'decimal.Decimal'>
    

and then

    
    
    >>> (Decimal('1.40') - Decimal('.3')) / Decimal('.05')
    Decimal('22')
    

The `fractions.Fraction` class would work too. Or, you could just round:

    
    
    >>> round((1.40-.3)/.05, 10) #  round to 10 decimal places
    22.0
    

