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:
ceil() The Math. ceil() function always rounds a number up to the next largest integer.
The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
round() The Math. round() function returns the value of a number rounded to the nearest integer.
Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.
import 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With