Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round up the result of integer division?

Tags:

java

c#

math

I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.

If I have x items which I want to display in chunks of y per page, how many pages will be needed?

like image 610
Ian Nelson Avatar asked Aug 20 '08 13:08

Ian Nelson


People also ask

How do you round up an integer?

If the digit in the tenths place is less than 5, then round down, which means the units digit remains the same; if the digit in the tenths place is 5 or greater, then round up, which means you should increase the unit digit by one.

Does C round up or down for integer division?

When doing an integer division in c++, the result will always be rounded down, so your rounding system isn't off :) For example even if you divide 1999 by 1000, the result will be 1 if both 1999 and 1000 are integers.

Does integer division round up in Java?

Java does a round down in case of division of two integer numbers.

What is the result of integer division?

The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.


1 Answers

Found an elegant solution:

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

Source: Number Conversion, Roland Backhouse, 2001

like image 173
Ian Nelson Avatar answered Oct 14 '22 00:10

Ian Nelson