Is there any native Python way to round up?
Example: 10/3
resulting in 4
.
What I'm using now is a conditional:
x=10
if x % 3 != 0:
x += 1
But that's not very practical.
Is there any native Python way to round up?
Example: 10/3
resulting in 4
.
What I'm using now is a conditional:
x=10
if x % 3 != 0:
x += 1
But that's not very practical.
Using pure mathematics whenever you want to round a number up add a whole unit of the value that you want the rounding to take and take the whole part, this will ensure that it always falls to the next value. But there is a problem that the question deals with, when it is already integer can not make the sum, then there is no escape from it:
x = x + (1 if x % int(x) else 0)
If you want you can use a Python ready function which is ceil()
that does knock on the ceiling:
x = ceil(x)
But note that this has some criteria, and they may even be more appropriate if you understand them. It may give a different result if it is negative or positive.
In the background the function will do these checks for you, not what you are doing less, it is just abstracting for you.
Try using math.ceil()
.
x = 10
x= x % 3
x = ceil(x)