Rounding a number to nearest even

Gerard Flanagan grflanagan at gmail.com
Fri Apr 11 08:14:13 EDT 2008


On Apr 11, 2:05 pm, Gerard Flanagan <grflana... at gmail.com> wrote:
> On Apr 11, 12:14 pm, bdsatish <bdsat... at gmail.com> 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 ?
>
> ------------------------------------------------
> def myround(x):
>     n = int(x)
>     if abs(x - n) == 0.5:
>         if n % 2:
>             #it's odd
>             return n + 1 - 2 * int(n<0)
>         else:
>             return n
>     else:
>         return round(x)
>
> ------------------------------------------------

In fact you can avoid the call to the builtin round:

------------------------------------------------
def myround(x):
    n = int(x)
    if abs(x - n) >= 0.5 and n % 2:
        return n + 1 - 2 * int(n<0)
    else:
        return n

assert myround(3.2) == 3
assert myround(3.6) == 4
assert myround(3.5) == 4
assert myround(2.5) == 2
assert myround(-0.5) == 0.0
assert myround(-1.5) == -2.0
assert myround(-1.3) == -1.0
assert myround(-1.8) == -2
assert myround(-2.5) ==  -2.0
------------------------------------------------



More information about the Python-list mailing list