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

Wayne Werner waynejwerner at gmail.com
Fri Oct 8 15:00:10 CEST 2010


On Fri, Oct 8, 2010 at 7:51 AM, Sithembewena Lloyd Dube
<zebra05 at gmail.com>wrote:

> Hi folks,
>
> Supposing I had the float 4.4348 and I wished to round it off to the
> nearest half-integer upwards or downwards, how would I go about it?
>

You can use round:

round(4.4348) -> 4.0

But if you want to specify the behavior you can do something like this:

x = 4.4348
if x % 1 >= 0.5:
   x = x/1+1
else:
   x = x/1

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101008/52c4e100/attachment.html>


More information about the Tutor mailing list