round() function strange behaviour

logistix logstx at bellatlantic.net
Sat Mar 9 18:57:02 EST 2002


I'm suprised this one isn't in the FAQ.
You're seeing the actual object and not a printable representation of it.

>>> round(56.78923, 2)
56.789999999999999
>>> print round(56.78923, 2)
56.79
>>> "%f" % round(56.78923, 2)
'56.790000'

--
-

<brobbins333 at shaw.ca> wrote in message news:3c8a9c23.152007063 at news...
> I understand the problem of rounding errors with binary numbers.
> However, the rounding functions of other languages  work around it and
> return a usable result. What have they got that Python hasn't got?
>
> BR
>
> ps -- your name is very familiar. i think i've read one of your books.
>
> On Sat, 09 Mar 2002 23:13:50 GMT, Erik de Castro Lopo
> <nospam at mega-nerd.com> wrote:
>
> >brobbins333 at shaw.ca wrote:
> >>
> >> the round() function will sometimes return a predictable result, as
> >> in:
> >>
> >> round(45.67891, 2)
> >> >>> 45.68
> >>
> >> but sometimes it will return something like:
> >>
> >> round(56.78923, 2)
> >> >>> 56.789999999999999
> >>
> >> 2.1 and 2.2 both behave this way on two different (Windows) computers.
> >> What's going on here?
> >
> >
> >What you will fins is that some numbers like 2, 0.25 etc can be
> >represented exactly in floating point format while others like
> >2/3 cannot.
> >
> >Thats just the way it is.
> >
> >Erik
> >--
> >+-----------------------------------------------------------+
> >  Erik de Castro Lopo  nospam at mega-nerd.com (Yes it's valid)
> >+-----------------------------------------------------------+
> >BSD:  A psychoactive drug, popular in the 80s, probably developed at UC
> >Berkeley or thereabouts.  Similar in many ways to the prescription-only
> >medication called "System V", but infinitely more useful. (Or, at least,
> >more fun.)  The full chemical name is "Berkeley Standard Distribution".
>





More information about the Python-list mailing list