Rounding a number to nearest even

bdsatish bdsatish at gmail.com
Fri Apr 11 08:33:53 EDT 2008


HI Gerard,

I think you've taken it to the best possible implementation. Thanks !
On Apr 11, 5:14 pm, Gerard Flanagan <grflana... at gmail.com> wrote:
> 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