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

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

[{'answer_id': 17949, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': -1, 'selected': False, 'text': "<p>You'll want to do floating point division, and then use the ceiling function, to round up the value to the next integer.</p>\n"}, {'answer_id': 17953, 'author': 'Jarod Elliott', 'author_id': 1061, 'author_profile': 'https://Stackoverflow.com/users/1061', 'pm_score': 2, 'selected': False, 'text': "<p>Another alternative is to use the mod() function (or '%'). If there is a non-zero remainder then increment the integer result of the division.</p>\n"}, {'answer_id': 17954, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 6, 'selected': False, 'text': '<p>This should give you what you want.  You will definitely want x items divided by y items per page, the problem is when uneven numbers come up, so if there is a partial page we also want to add one page.</p>\n\n<pre><code>int x = number_of_items;\nint y = items_per_page;\n\n// with out library\nint pages = x/y + (x % y &gt; 0 ? 1 : 0)\n\n// with library\nint pages = (int)Math.Ceiling((double)x / (double)y);\n</code></pre>\n'}, {'answer_id': 17957, 'author': 'Huppie', 'author_id': 1830, 'author_profile': 'https://Stackoverflow.com/users/1830', 'pm_score': 7, 'selected': False, 'text': '<p>For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):</p>\n\n<pre><code>int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);\n</code></pre>\n\n<p>In java you should do the same with Math.ceil().</p>\n'}, {'answer_id': 17974, 'author': 'Ian Nelson', 'author_id': 2084, 'author_profile': 'https://Stackoverflow.com/users/2084', 'pm_score': 10, 'selected': True, 'text': '<p>Found an elegant solution:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>Source: <a href="http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf" rel="noreferrer">Number Conversion, Roland Backhouse, 2001</a></p>\n'}, {'answer_id': 96921, 'author': 'Brandon DuRette', 'author_id': 17834, 'author_profile': 'https://Stackoverflow.com/users/17834', 'pm_score': 4, 'selected': False, 'text': '<p>The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all <code>int</code>, the solution could be rewritten to use <code>long</code> math and avoid the bug:</p>\n\n<p><code>int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;</code></p>\n\n<p>If <code>records</code> is a <code>long</code>, the bug remains. The modulus solution does not have the bug.</p>\n'}, {'answer_id': 503201, 'author': 'rjmunro', 'author_id': 3408, 'author_profile': 'https://Stackoverflow.com/users/3408', 'pm_score': 8, 'selected': False, 'text': "<p>Converting to floating point and back seems like a huge waste of time at the CPU level.</p>\n\n<p>Ian Nelson's solution:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>int pageCount = (records - 1) / recordsPerPage + 1;\n</code></pre>\n\n<p>AFAICS, this doesn't have the overflow bug that Brandon DuRette pointed out, and because it only uses it once, you don't need to store the recordsPerPage specially if it comes from  an expensive function to fetch the value from a config file or something.</p>\n\n<p>I.e. this might be inefficient, if config.fetch_value used a database lookup or something:</p>\n\n<pre><code>int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');\n</code></pre>\n\n<p>This creates a variable you don't really need, which probably has (minor) memory implications and is just too much typing:</p>\n\n<pre><code>int recordsPerPage = config.fetch_value('records per page')\nint pageCount = (records + recordsPerPage - 1) / recordsPerPage;\n</code></pre>\n\n<p>This is all one line, and only fetches the data once:</p>\n\n<pre><code>int pageCount = (records - 1) / config.fetch_value('records per page') + 1;\n</code></pre>\n"}, {'answer_id': 536219, 'author': 'Mike', 'author_id': 65004, 'author_profile': 'https://Stackoverflow.com/users/65004', 'pm_score': 2, 'selected': False, 'text': "<p>For records == 0, rjmunro's solution gives 1.  The correct solution is 0.  That said, if you know that records > 0 (and I'm sure we've all assumed recordsPerPage > 0), then rjmunro solution gives correct results and does not have any of the overflow issues.</p>\n\n<pre><code>int pageCount = 0;\nif (records &gt; 0)\n{\n    pageCount = (((records - 1) / recordsPerPage) + 1);\n}\n// no else required\n</code></pre>\n\n<p><strong>All</strong> the integer math solutions are going to be more efficient than <em>any</em> of the floating point solutions.</p>\n"}, {'answer_id': 3473687, 'author': 'flux', 'author_id': 228406, 'author_profile': 'https://Stackoverflow.com/users/228406', 'pm_score': 0, 'selected': False, 'text': '<p>Alternative to remove branching in testing for zero:</p>\n\n<pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);\n</code></pre>\n\n<p>Not sure if this will work in C#, should do in C/C++.</p>\n'}, {'answer_id': 4043686, 'author': 'Jeremy Hadfied', 'author_id': 490178, 'author_profile': 'https://Stackoverflow.com/users/490178', 'pm_score': -1, 'selected': False, 'text': '<p>A generic method, whose result you can iterate over may be of interest:</p>\n\n<pre><code>public static Object[][] chunk(Object[] src, int chunkSize) {\n\n    int overflow = src.length%chunkSize;\n    int numChunks = (src.length/chunkSize) + (overflow&gt;0?1:0);\n    Object[][] dest = new Object[numChunks][];      \n    for (int i=0; i&lt;numChunks; i++) {\n        dest[i] = new Object[ (i&lt;numChunks-1 || overflow==0) ? chunkSize : overflow ];\n        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); \n    }\n    return dest;\n}\n</code></pre>\n'}, {'answer_id': 5883806, 'author': 'finnw', 'author_id': 12048, 'author_profile': 'https://Stackoverflow.com/users/12048', 'pm_score': 3, 'selected': False, 'text': '<p>A variant of <a href="https://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division/17954#17954">Nick Berardi\'s answer</a> that avoids a branch:</p>\n\n<pre><code>int q = records / recordsPerPage, r = records % recordsPerPage;\nint pageCount = q - (-r &gt;&gt; (Integer.SIZE - 1));\n</code></pre>\n\n<p>Note: <code>(-r &gt;&gt; (Integer.SIZE - 1))</code> consists of the sign bit of <code>r</code>, repeated 32 times (thanks to sign extension of the <code>&gt;&gt;</code> operator.)  This evaluates to 0 if <code>r</code> is zero or negative, -1 if <code>r</code> is positive.  So subtracting it from <code>q</code> has the effect of adding 1 if <code>records % recordsPerPage &gt; 0</code>.</p>\n'}, {'answer_id': 9771364, 'author': 'Richard Parsons', 'author_id': 1278685, 'author_profile': 'https://Stackoverflow.com/users/1278685', 'pm_score': -1, 'selected': False, 'text': '<p>I had a similar need where I needed to convert Minutes to hours &amp; minutes. What I used was:</p>\n\n<pre><code>int hrs = 0; int mins = 0;\n\nfloat tm = totalmins;\n\nif ( tm &gt; 60 ) ( hrs = (int) (tm / 60);\n\nmins = (int) (tm - (hrs * 60));\n\nSystem.out.println("Total time in Hours &amp; Minutes = " + hrs + ":" + mins);\n</code></pre>\n'}, {'answer_id': 14754238, 'author': 'Jim Watson', 'author_id': 2051259, 'author_profile': 'https://Stackoverflow.com/users/2051259', 'pm_score': -1, 'selected': False, 'text': '<p>The following should do rounding better than the above solutions, but at the expense of performance (due to floating point calculation of 0.5*rctDenominator):</p>\n\n<pre><code>uint64_t integerDivide( const uint64_t&amp; rctNumerator, const uint64_t&amp; rctDenominator )\n{\n  // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)\n  return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;\n}\n</code></pre>\n'}, {'answer_id': 21548669, 'author': 'Sam Jones', 'author_id': 1428089, 'author_profile': 'https://Stackoverflow.com/users/1428089', 'pm_score': 2, 'selected': False, 'text': "<p>I do the following, handles any overflows:</p>\n\n<pre><code>var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;\n</code></pre>\n\n<p>And use this extension for if there's 0 results:</p>\n\n<pre><code>public static bool IsDivisble(this int x, int n)\n{\n           return (x%n) == 0;\n}\n</code></pre>\n\n<p>Also, for the current page number (wasn't asked but could be useful):</p>\n\n<pre><code>var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;\n</code></pre>\n"}, {'answer_id': 39519292, 'author': 'Nicholas Petersen', 'author_id': 264031, 'author_profile': 'https://Stackoverflow.com/users/264031', 'pm_score': 3, 'selected': False, 'text': "<p>In need of an extension method: </p>\n\n<pre><code>    public static int DivideUp(this int dividend, int divisor)\n    {\n        return (dividend + (divisor - 1)) / divisor;\n    }\n</code></pre>\n\n<p>No checks here (overflow, <code>DivideByZero</code>, etc), feel free to add if you like. By the way, for those worried about method invocation overhead, simple functions like this might be inlined by the compiler anyways, so I don't think that's where to be concerned. Cheers.</p>\n\n<p>P.S. you might find it useful to be aware of this as well (it gets the remainder): </p>\n\n<pre><code>    int remainder; \n    int result = Math.DivRem(dividend, divisor, out remainder);\n</code></pre>\n"}, {'answer_id': 63012251, 'author': 'SendETHToThisAddress', 'author_id': 5835002, 'author_profile': 'https://Stackoverflow.com/users/5835002', 'pm_score': 3, 'selected': False, 'text': '<p><strong>HOW TO ROUND UP THE RESULT OF INTEGER DIVISION IN C#</strong></p>\n<p>I was interested to know what the best way is to do this in C# since I need to do this in a loop up to nearly 100k times. Solutions posted by others using <em>Math</em> are ranked high in the answers, but in testing I found them slow. Jarod Elliott proposed a better tactic in checking if mod produces anything.</p>\n<pre><code>int result = (int1 / int2);\nif (int1 % int2 != 0) { result++; }\n</code></pre>\n<p>I ran this in a loop 1 million times and it took 8ms. Here is the code using <em>Math</em>:</p>\n<pre><code>int result = (int)Math.Ceiling((double)int1 / (double)int2);\n</code></pre>\n<p>Which ran at 14ms in my testing, considerably longer.</p>\n'}, {'answer_id': 69479389, 'author': 'H.M.Mubashir', 'author_id': 16925201, 'author_profile': 'https://Stackoverflow.com/users/16925201', 'pm_score': 2, 'selected': False, 'text': '<p>you can use</p>\n<pre><code>(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));\n</code></pre>\n'}, {'answer_id': 74147725, 'author': 'Jin-K', 'author_id': 7210166, 'author_profile': 'https://Stackoverflow.com/users/7210166', 'pm_score': 0, 'selected': False, 'text': '<p>I made this for me, thanks to <a href="https://stackoverflow.com/a/17953/7210166">Jarod Elliott</a> &amp; <a href="https://stackoverflow.com/a/63012251/7210166">SendETHToThisAddress</a> replies.</p>\n<pre><code>public static int RoundedUpDivisionBy(this int @this, int divider)\n{        \n    var result = @this / divider;\n    if (@this % divider is 0) return result;\n    return result + Math.Sign(@this * divider);\n}\n</code></pre>\n<p>Then I realized it is overkill for the CPU compared to the top answer.\nHowever, I think it\'s readable and works with negative numbers as well.</p>\n'}]
['https://Stackoverflow.com/questions/17944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2084/']