How to use the python round

1

When I use the python round it converts 1.5 to 2, but with 2.5 it leaves 2. How do I round 2.5 to 3? Being that any other number that does not contain the number 2 it rounds right

    
asked by anonymous 02.02.2018 / 18:03

1 answer

2

The round takes its value to the nearest even integer.

To round up, use math.ceil :

import math
print(math.ceil(1.5))  # 2.0
print(math.ceil(2.5))  # 3.0

To round 0.5 up and 0.49999 down, you can do a function with the module decimal :

import decimal

def arredondar(x):
    return int(decimal.Decimal(x).quantize(0, decimal.ROUND_HALF_UP))

print(arredondar(1.5))  # 2
print(arredondar(2.5))  # 3
print(arredondar(1.4))  # 1
print(arredondar(2.4))  # 2
    
02.02.2018 / 18:08