Coder Perfect

How do you round up an integer division result?


When utilizing a language like C# or Java, I’m thinking about how to display pagination controls in particular.

How many pages will be required if I have x items to present in chunks of y per page?

Asked by Ian Nelson

Solution #1

I came up with a clever solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

Roland Backhouse, Number Conversion, 2001.

Answered by Ian Nelson

Solution #2

At the CPU level, converting to and from floating point appears to be a significant waste of effort.

Ian Nelson’s solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

It’s possible to reduce it to:

int pageCount = (records - 1) / recordsPerPage + 1;

As far as I can see, this doesn’t have the overflow bug that Brandon DuRette mentioned, and because it’s only used once, you don’t need to keep the recordsPerPage value, especially if it’s from an expensive function to get the value from a config file or something.

If config.fetch value used a database lookup or anything, this could be inefficient:

int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');

This generates a variable you don’t need, has (small) memory consequences, and is simply too much typing:

int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

This is all on one line, and the data is only fetched once:

int pageCount = (records - 1) / config.fetch_value('records per page') + 1;

Answered by rjmunro

Solution #3

The answer in C# is to cast the values to a double (because Math.Ceiling accepts a double):

int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);

You should use Math.ceil in Java to accomplish the same thing ().

Answered by Huppie

Solution #4

This should provide you with the results you seek. You’ll surely want x items split by y things per page; the issue arises when the numbers are unequal; therefore, if a partial page exists, we’ll also want to add one page.

int x = number_of_items;
int y = items_per_page;

// with out library
int pages = x/y + (x % y > 0 ? 1 : 0)

// with library
int pages = (int)Math.Ceiling((double)x / (double)y);

Answered by Nick Berardi

Solution #5

The integer math solution offered by Ian is good, but it has an integer overflow problem. Assuming that all of the variables are int, the solution could be rewritten to avoid the error by using long math:

pageCount = (-1L + records + recordsPerPage) / recordsPerPage; int pageCount = (-1L + records + recordsPerPage) / recordsPerPage; int pageCount = (-1L +

If the list of records is too long, the bug persists. The bug does not exist in the modulus solution.

Answered by Brandon DuRette

Post is based on