# Rounding a number to nearest even

bdsatish bdsatish at gmail.com
Fri Apr 11 13:07:51 CEST 2008

```On Apr 11, 3:27 pm, colas.fran... at gmail.com wrote:
> 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?

No. not at all. The clause "nearest even" comes into picture only when
a number is of form "x.5" or else it's same as builtin round( ).
new_round(3.0) must be 3.0 itself. Here is the mathematical definition
of what I want:

If 'n' is an integer,

new_round(n+0.5) = n  if  n/2 is integer
new_round(n+0.5) = (n+1) if  (n+1)/2 is integer

In all other cases, new_round() behave similarly as round( ). Here are
the results I expect:

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

The built-in function doesnt meet my needs for round(-2.5) or
round(2.5)

```