Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round away from 0 in Python 3.x?

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?

like image 372
planetp Avatar asked Aug 04 '18 21:08

planetp


People also ask

How do you round off in Python 3?

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.

How do you round 0 in Python?

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.

Does Python round 0.5 up or down?

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.

How do you round a number to the next 10 in Python?

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.


2 Answers

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
like image 106
kristaps Avatar answered Oct 24 '22 12:10

kristaps


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)
like image 34
AGN Gazer Avatar answered Oct 24 '22 11:10

AGN Gazer