# Rounding a number to nearest even

Chris cwitts at gmail.com
Tue Apr 15 12:47:11 CEST 2008

```On Apr 15, 12:33 pm, Chris <cwi... at gmail.com> wrote:
> On Apr 15, 11:47 am, Duncan Booth <duncan.bo... at invalid.invalid>
> wrote:
>
> > Chris <cwi... at gmail.com> wrote:
> > > even is closer to even.75 than even+1.25.  Why should it be rounded
> > > up ?
>
> > Because the OP wants to round values to the nearest integer. Only values of
> > the form 'x.5' which have two nearest values use 'nearest even' to
> > disambiguate the result.
>
> > Seehttp://en.wikipedia.org/wiki/Rounding#Round-to-even_method
>
> > That's the way I was taught to round numbers when at primary school.
>
> My bad, didn't see he only wanted for halves and handle others as
> normal.

My contribution then:

def my_round(x):
if x < 0:
NEG = 1
x = -x
else:
NEG = 0
if not x%.5 and not int(x)%2:
if NEG: return -round(x-.1)
return round(x-.1)
elif not x%.5 and int(x)%2:
if NEG: return -round(x+.1)
return round(x+.1)
elif NEG:
return round(-x)
else:
return round(x)

[(f*.25, my_round(f*.25)) for f in xrange(-20,20)]

[(-5.0, -5.0), (-4.75, -5.0), (-4.5, -4.0), (-4.25, -4.0), (-4.0,
-4.0), (-3.75, -4.0), (-3.5, -4.0), (-3.25, -3.0), (-3.0, -3.0),
(-2.75, -3.0), (-2.5, -2.0), (-2.25, -2.0), (-2.0, -2.0), (-1.75,
-2.0), (-1.5, -2.0), (-1.25, -1.0), (-1.0, -1.0), (-0.75, -1.0),
(-0.5, 0.0), (-0.25, 0.0), (0.0, 0.0), (0.25, 0.0), (0.5, 0.0), (0.75,
1.0), (1.0, 1.0), (1.25, 1.0), (1.5, 2.0), (1.75, 2.0), (2.0, 2.0),
(2.25, 2.0), (2.5, 2.0), (2.75, 3.0), (3.0, 3.0), (3.25, 3.0), (3.5,
4.0), (3.75, 4.0), (4.0, 4.0), (4.25, 4.0), (4.5, 4.0), (4.75, 5.0)]

```