# [Tutor] Rounding a Python float to the nearest half integer

Evert Rol evert.rol at gmail.com
Fri Oct 8 16:50:03 CEST 2010

```> @Evert, I didn't figure out that your response was a solution, thought it was a question. Must be coffee time :P
>
> I tried it and, for instance, the rounded value (9) / 2 gave me 4.0 Couldn't get it until I noticed that @Joel divided the roudned figure by a decimal 2.0. That gave 4.5, which is what I was looking for.

How do you get a rounded value of 9 (integer)? Round() returns a float, afaik; ie, you wouldn't the the 2.0, but just 2. (In fact, your return value is 4.0, which for integer division wouldn't work. So something was odd there, but I can't think of what.)

Also, perhaps better to use
from __future__ import division
to prevent these mistakes.

Cheers,

Evert

> > I realise that one cannot have a half integer :) I meant how would one round off to the first decimal nearest to either 0.5, or a whole number.
> >
> > Ugh...does anyone get what I'm trying to articulate? :)
>
> Multiply by 2, round(), divide by 2?
>
> That sounds like a good idea:
>
> >>> n = [1.0 + x/10.0 for x in range(10)]  # get some numbers to test
> >>> n
> [1.0, 1.1000000000000001, 1.2, 1.3, 1.3999999999999999, 1.5, 1.6000000000000001, 1.7, 1.8, 1.8999999999999999]
> >>> r = [round(2*x)/2.0 for x in n]   # double, round, then divide by 2.0
> >>> r
> [1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0]
> >>>
>
>
> --
> Joel Goldstick
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> --
> Regards,
> Sithembewena Lloyd Dube
> http://www.lloyddube.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

```