Integer Division

Chris Rebert clp2 at rebertia.com
Fri Jun 19 03:27:00 EDT 2009


On Fri, Jun 19, 2009 at 12:22 AM, Anjanesh
Lekshminarayanan<mail at anjanesh.net> wrote:
>>>> a = 1
>>>> b = 25
>>>> a / b
> 0
>>>> float(a) / b
> 0.040000000000000001
>>>>
>
>>>> from __future__ import division
>>>> a = 1
>>>> b = 25
>>>> a / b
> 0.040000000000000001
>>>>
>
> In what simple way can I get just 0.04 ?

Note that what you are shown is the repr() of the float rather than
the str() of the float. The repr() value is what the number truly is
in binary, but str() applies more sensible rounding.

Example (remember that print() does an implicit str()):
>>> from __future__ import division
>>> print(1/25)
0.04
>>> repr(1/25)
0.040000000000000001
>>>

Alternatively, you can use the decimal arithmetic library:
>>> from decimal import Decimal
>>> Decimal(1)/Decimal(25)
Decimal('0.04')
>>>

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list