[Tutor] round() errors

Ignacio Vazquez-Abrams ignacio@openservices.net
Wed, 12 Sep 2001 16:42:44 -0400 (EDT)


On Wed, 12 Sep 2001, Christian Mascher wrote:

> Hi All,
>
> I don't understand some response from the round()-function.
>
> >>> round(1.4783321399,2)
> 1.48
> >>> round(1.95583,2) # this is the ratio of EURO to DM
> 1.96
>
> so far, so good, but ...
>
> >>> round(10*1.95583,2)
> 19.559999999999999
> >>> round(20*1.95583,2)
> 39.119999999999997
> >>> a=20*1.95583
> >>> a
> 39.116599999999998
> >>> round(a,2)
> 39.119999999999997
>
> I recall reading somebody explain this behaviour with the problem of
> representing base-10 float-numbers in a binary system. Still, I ask
> myself, why can't round() be smart enough to handle this on its own
> (especially the last case)?
> Since you can do
>
> >>> print '%.2f' %a
> 39.12
> >>>
>
> why can't round() do the same? Is there any reason?

It's because round() returns a floating-point number, whereas format
specifiers convert it to a string.

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>