In Python 2 rounding is done away from 0
, so, for example, round(0.5)
is 1.0
.
In Python 3.x, however, rounding is done toward the even choice, so round(0.5)
is 0
.
What function can I use in Python 3.x to get the old behavior?
Python round() Function The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.
Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.
For <0.5, it rounds down, and for >0.5, it rounds up. For =0.5, the round() function rounds the number off to the nearest even number. So, 0.5 is rounded to zero, and so is -0.5; 33.5 and 34.5 are both rounded off to 34; -33.5 -34.5 are both rounded off to -34, and so on.
Use the round() function to round a number to the nearest 10, e.g. result = round(num, -1) . When the round() function is called with a second argument of -1 , it rounds to the closest multiple of 10.
If your code is not particularly performance sensitive, you can use the standard decimal
library to achieve the result you want. Decimal().quantize()
allows choosing the rounding method:
from decimal import Decimal, ROUND_HALF_UP
result = float(Decimal(0.5).quantize(Decimal(0), rounding=ROUND_HALF_UP))
print(result) # Will output 1.0
Equivalent of Python 2.7 round()
when rounding to an integer (one-parameter):
import math
def py2round(x):
if x >= 0.0:
return math.floor(x + 0.5)
else:
return math.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