How to use python round

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

Author: Coelho, 2018-02-02

1 answers

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 make 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
 2
Author: Pedro von Hertwig Batista, 2018-02-02 17:26:59