11
votes

It's basically returning the boxes_needed. 1 box can contain 10 items. So if the items typed by the user is 102 then the code should return 11 boxes.

Is there a way to divide that rounds upwards if there is a non-zero remainder?

4
is this what you want ceil(10.4) - The6thSense
Use the "convert floor division to ceiling division operator", which is spelled "--0--" Example usage: --0-- 102//10 -> 11. (Try it!) </tongue-in-cheek>. More seriously, this is just a disguised variant on Stefan Pochmann's answer, which not only gives the right result for integers but also extends correctly to other number types, like float and Fraction. - Mark Dickinson
For anyone else parsing this: it parses as - (-0) - (-102)//10. The same effect can be achieved with 0-- 102//10. --102//10 fails because it parses as (- ( - 102)) // 10. - rhaps0dy

4 Answers

27
votes

For your use case, use integer arithmetic. There is a simple technique for converting integer floor division into ceiling division:

items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize

Alternatively, use negation to convert floor division to ceiling division:

num_boxes = -(items // -boxsize)
20
votes

Negate before and after?

>>> -(-102 // 10)
11
2
votes
from math import ceil

print(ceil(10.3))

11
0
votes

You can try :

import math
math.ceil( x )