0

I would like to know how do we round up a number on python without using the math.ceil function. I have tried to use a condition "if" but it doesn't work. for example : 4.01 would become 5 and 4.0 would stay 4. How do we do that please ? Thank you

4 Answers4

4
round(x + 0.5)

Check that this works for 1.0, 2.0, 3.0 etc to make sure that .5 always rounds down.

If not, convert to an Int and if the original is greater, add one.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
3

you can create a function to do this

def ceil(f): 
  return int(f) + (1 if f-int(f) else 0)
 
kiranr
  • 2,087
  • 14
  • 32
1

you could try using the round() function:

a =2.22
round(a) # 2

b = 5.89
round(b) # 6
 
Orozco
  • 375
  • 2
  • 8
1

You can check if the number is a integer if the x%int(x) == 0. If it is, do do nothing, else, return the integer plus 1:

rd = lambda x: int(x) if x%int(x) == 0 else int(x) + 1
#rd(4.1) = 5
#rd(4) = 4
Filipe
  • 169
  • 5