How to truncate/round-off decimal numbers?

Laurent Pointal laurent.pointal at limsi.fr
Tue Jun 20 05:29:16 EDT 2006


Girish Sahani a écrit :
> Hi,
> 
> I want to truncate every number to 2 digits after the decimal point. I
> tried the following but it doesnt work.
> 
>>>> 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.

There are two operations:

1) calculate of round(), which return a float number result, with the
well known problem of floating point numbers represantation (see the FAQ).

2) print that number, where default printing of last expression result
in the cli interpreter displays up to the highest precision, print
statement works differently:

>>> a=2
>>> b=3
>>> c=round(a*1.0/b,2)
>>> c
0.67000000000000004
>>> print c
0.67
>>>

A+

Laurent.



More information about the Python-list mailing list