Rounding a number to nearest even

colas.francis at gmail.com colas.francis at gmail.com
Fri Apr 11 12:27:44 CEST 2008


On 11 avr, 12:14, 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 ?

When you say "round to the nearest even", you mean new_round(3) <> 3?

Is so, you can try:

In [37]: def new_round(x):
   ....:     return round(x/2.)*2
   ....:

In [38]: new_round(1.5)
Out[38]: 2.0

In [39]: new_round(2.5)
Out[39]: 2.0

In [40]: new_round(3)
Out[40]: 4.0



More information about the Python-list mailing list