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

Joel Goldstick joel.goldstick at gmail.com
Fri Oct 8 15:35:25 CEST 2010


On Fri, Oct 8, 2010 at 9:00 AM, Evert Rol <evert.rol at gmail.com> wrote:

> > 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101008/f05f346d/attachment-0001.html>


More information about the Tutor mailing list