how to always round up to the next integer [duplicate]
i am trying to find total pages in building a pager on a website (so i want the result to be an integer. i get a list of records and i want to split into 10 per page (the page count)
when i do this:
list.Count() / 10
or
list.Count() / (decimal)10
and the list.Count() =12
, i get a result of 1
.
How would I code it so i get 2
in this case (the remainder should always add 1
)
Solution 1:
Math.Ceiling((double)list.Count() / 10);
Solution 2:
(list.Count() + 9) / 10
Everything else here is either overkill or simply wrong (except for bestsss' answer, which is awesome). We do not want the overhead of a function call (Math.Truncate()
, Math.Ceiling()
, etc.) when simple math is enough.
OP's question generalizes (pigeonhole principle) to:
How many boxes do I need to store
x
objects if onlyy
objects fit into each box?
The solution:
- derives from the realization that the last box might be partially empty, and
- is
(x + y - 1) ÷ y
using integer division.
You'll recall from 3rd grade math that integer division is what we're doing when we say 5 ÷ 2 = 2
.
Floating-point division is when we say 5 ÷ 2 = 2.5
, but we don't want that here.
Many programming languages support integer division. In languages derived from C, you get it automatically when you divide int
types (short
, int
, long
, etc.). The remainder/fractional part of any division operation is simply dropped, thus:
5 / 2 == 2
Replacing our original question with x = 5
and y = 2
we have:
How many boxes do I need to store 5 objects if only 2 objects fit into each box?
The answer should now be obvious: 3 boxes
-- the first two boxes hold two objects each and the last box holds one.
(x + y - 1) ÷ y =
(5 + 2 - 1) ÷ 2 =
6 ÷ 2 =
3
So for the original question, x = list.Count()
, y = 10
, which gives the solution using no additional function calls:
(list.Count() + 9) / 10