How to truncate/round-off decimal numbers?

MTD marc.t.davies at gmail.com
Tue Jun 20 05:24:41 EDT 2006


> >>> a = 2
> >>> b = 3
> >>> round(a*1.0 / b,2)
> 0.67000000000000004
>
> Inspite of specifying 2 in 2nd attribute of round, it outputs all the
> digits after decimal.

This is because of floating point inaccuracy. The system cannot
accurately represent some integers, however it does its best to
approximate them. Notice this:

>>> x = 2.0/3
>>> x
0.66666666666666663
>>> round(x,2)
0.67000000000000004
>>> s = str(round(x,2))
>>> s
'0.67'




More information about the Python-list mailing list