How to use python round

Asked

Viewed 2,290 times

1

When I use the python round it converts 1.5 to 2, but with 2.5 it leaves 2. How do I make it round 2.5 to 3 ? Where any number other than the number 2

1 answer

2


The round takes its value to the nearest even integer.

To round up, use the 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
  • But then I can’t do what I want. I want to enter a number and if the house after the '.' is less than 4 round down and if it is greater than 5 round up. You’d know how I can do that ?

  • @Rabbit see if now understood; I edited the answer!

  • Thanks friend.

  • @Rabbit for nothing! Don’t forget to accept the answer if she answered your question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.