Rounding a number to nearest even

colas.francis at gmail.com colas.francis at gmail.com
Tue Apr 15 05:37:28 EDT 2008


On 14 avr, 20:02, Thomas Dybdahl Ahle <lob... at gmail.com> wrote:
> On Fri, 2008-04-11 at 03:14 -0700, bdsatish wrote:
> > The built-in function round( ) will always "round up", that is 1.5 is
> > rounded to 2.0 and 2.5 is rounded to 3.0.
>
> > If I want to round to the nearest even, that is
>
> > my_round(1.5) = 2        # As expected
> > my_round(2.5) = 2        # Not 3, which is an odd num
>
> > I'm interested in rounding numbers of the form "x.5" depending upon
> > whether x is odd or even. Any idea about how to implement it ?
>
> This seams to work fine:
> evenRound = lambda f: round(f/2.)*2

That was the solution I proposed first but it is inadequate since the
op does not want 3 to be rounded to 4.
If you're interested in this discussion, I kindly suggest you read the
whole thread: many interesting proposals and discussions have ensued.




More information about the Python-list mailing list