Where is the correct round() method?

josh logan dear.jay.logan at gmail.com
Mon Jul 28 02:48:08 CEST 2008


On Jul 27, 7:58 pm, Gary Herron <gher... at islandtraining.com> wrote:
> josh logan wrote:
> > Hello,
>
> > I need a round function that _always_ rounds to the higher integer if
> > the argument is equidistant between two integers. In Python 3.0, this
> > is not the advertised behavior of the built-in function round() as
> > seen below:
>
> >>>> round(0.5)
>
> > 0
>
> >>>> round(1.5)
>
> > 2
>
> >>>> round(2.5)
>
> > 2
>
> Huh?
>
>  >>> round(2.5)
> 3.0
>
> Works for me on Python 2.5 on Linux running on "Intel(R) Core(TM)2 Duo
> CPU".  What system are you on?
>
> It could be that 2.5 is really 2.49999... which would round down to 2,
> but on any modern CPU (using IEEE floating point), 2.5 should be
> representable exactly.
>
> However, as with any floating point calculations, if you expect exact
> representation or calculations with any numbers, then you are misusing
> floating points.
>
> Gary Herron
>
> > I would think this is a common need, but I cannot find a function in
> > the Python library to do it. I wrote my own, but did I miss such a
> > method in my search of the Python library?
>
> > Thanks
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

I should reiterate that I am using Python 3.0 and not Python 2.x.
It looks like the behavior round() has changed between these two
versions.
Here is the documentation for round() in Python 3.0:
http://docs.python.org/dev/3.0/library/functions.html#round

Of interest in this discussion is the second paragraph, which explains
the change:

Does anyone know the reason behind this change, and what replacement
method I can use to get the original behavior?



More information about the Python-list mailing list