Pythonic way to "round()" like Javascript "Math.round()"? Pythonic way to "round()" like Javascript "Math.round()"? python-3.x python-3.x

Pythonic way to "round()" like Javascript "Math.round()"?


import mathdef roundthemnumbers(value):    x = math.floor(value)    if (value - x) < .50:        return x    else:        return math.ceil(value)

Haven't had my coffee yet, but that function should do what you need. Maybe with some minor revisions.


The behavior of Python's round function changed between Python 2 and Python 3. But it looks like you want the following, which will work in either version:

math.floor(x + 0.5)

This should produce the behavior you want.


Instead of using round() function in python you can use the floor function and ceil function in python to accomplish your task.

floor(x+0.5)

or

ceil(x-0.5)