Where is the correct round() method?

Casey Caseyweb at gmail.com
Mon Jul 28 09:42:39 EDT 2008


On Jul 28, 12:34 am, Gary Herron <gher... at islandtraining.com> wrote:

> This will work as you wish:
>   math.floor(x+0.5)

This works fine for positive x but what about negative:

>>> round(2.5)
3.0
>>> floor(2.5 + 0.5)
3.0
>>> round(-2.5)
-3.0
>>> floor(-2.5 + 0.5)
-2.0

Maybe:

def round2(x):
    return math.floor(x + (0.5 if x >= 0 else -0.5))



More information about the Python-list mailing list