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
Asked
Active
Viewed 2,141 times
0
-
1Can you show your relevant code? Whatever you have done so far and where exactly you are stuck? – Girish Feb 03 '21 at 13:45
-
`round(x + 0.5)` or `x//1 + (x%1 > 0)` – h4z3 Feb 03 '21 at 13:53
-
There's plenty of answers in the linked duplicate that don't use `math.ceil` – DavidW Feb 03 '21 at 13:58
4 Answers
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
-
3OP wants the number to be rounded always up, while your example clearly shows normal rounding – h4z3 Feb 03 '21 at 13:48
-
You can also enter a second argument to choose how many decimals, like round(2.22,1) = 2.2 – Filipe Feb 03 '21 at 13:49
-
-
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