I want the most Pythonic way to round numbers just like Javascript does (through Math.round()
). They're actually slightly different, but this difference can make huge difference for my application.
Using round()
method from Python 3:
// Returns the value 20
x = round(20.49)
// Returns the value 20
x = round(20.5)
// Returns the value -20
x = round(-20.5)
// Returns the value -21
x = round(-20.51)
Using Math.round()
method from Javascript*:
// Returns the value 20
x = Math.round(20.49);
// Returns the value 21
x = Math.round(20.5);
// Returns the value -20
x = Math.round(-20.5);
// Returns the value -21
x = Math.round(-20.51);
Thank you!
References:
- Math.round() explanation at Mozilla Developers Network (MDN)
I want the most Pythonic way to round numbers just like Javascript does (through Math.round()
). They're actually slightly different, but this difference can make huge difference for my application.
Using round()
method from Python 3:
// Returns the value 20
x = round(20.49)
// Returns the value 20
x = round(20.5)
// Returns the value -20
x = round(-20.5)
// Returns the value -21
x = round(-20.51)
Using Math.round()
method from Javascript*:
// Returns the value 20
x = Math.round(20.49);
// Returns the value 21
x = Math.round(20.5);
// Returns the value -20
x = Math.round(-20.5);
// Returns the value -21
x = Math.round(-20.51);
Thank you!
References:
- Math.round() explanation at Mozilla Developers Network (MDN)
- 3 Please specify which version of python you are using, as this may be different between python 2 and python 3. – khelwood Commented Jan 19, 2016 at 12:21
- First of all, why the negative point without any explanation about that? And thank you @khelwood, I'll provide the information. – Paladini Commented Jan 19, 2016 at 12:22
- 3 This question and its answers might shade light on the situation. – MB-F Commented Jan 19, 2016 at 12:24
- I've updated the question to include the Python version! – Paladini Commented Jan 19, 2016 at 12:26
- 1 Thank you for the linked question, @kazemakase . Now I understand why Python3 choose to round numbers this way. – Paladini Commented Jan 19, 2016 at 12:35
3 Answers
Reset to default 12import math
def 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)