pagination
pages calculation
total pages
logic
coding

pagination logic in calculating total of pages

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The main pagination question is simple: given a total number of items and a page size, how many pages do you need? The correct calculation uses ceiling logic, because leftover items that do not fill a complete page still require another page.

The Core Formula

If you have 95 items and show 10 per page, the answer is not 9. It is 10, because the final 5 items still need a page.

The direct formula is:

totalPages = ceil(totalItems / itemsPerPage)

In JavaScript:

javascript
1function getTotalPages(totalItems, itemsPerPage) {
2  if (itemsPerPage <= 0) {
3    throw new Error('itemsPerPage must be greater than zero');
4  }
5
6  return Math.ceil(totalItems / itemsPerPage);
7}
8
9console.log(getTotalPages(95, 10)); // 10

This is the standard answer in most applications.

Integer-Only Version

Some codebases prefer integer arithmetic instead of floating-point ceiling. The equivalent formula is:

python
1def get_total_pages(total_items: int, items_per_page: int) -> int:
2    if items_per_page <= 0:
3        raise ValueError("items_per_page must be greater than zero")
4
5    return (total_items + items_per_page - 1) // items_per_page
6
7
8print(get_total_pages(95, 10))  # 10

Adding items_per_page - 1 before integer division simulates the ceiling effect.

Decide What Zero Items Means

One subtle part of pagination is the empty dataset. Mathematically, 0 items means 0 pages. Some user interfaces still choose to display one empty page for consistency, but that is a product choice rather than a math rule.

A clean implementation should make that behavior explicit:

javascript
1function getTotalPages(totalItems, itemsPerPage) {
2  if (itemsPerPage <= 0) {
3    throw new Error('itemsPerPage must be greater than zero');
4  }
5
6  if (totalItems === 0) {
7    return 0;
8  }
9
10  return Math.ceil(totalItems / itemsPerPage);
11}

The important part is consistency between the API, the UI, and the surrounding pagination logic.

Total Pages and Offsets

Once you know the total page count, you often also need the offset for a query. For one-based page numbers, the offset is:

javascript
1function getOffset(currentPage, itemsPerPage) {
2  return (currentPage - 1) * itemsPerPage;
3}
4
5console.log(getOffset(3, 10)); // 20

That means page 3 starts at offset 20, which corresponds to the twenty-first item in human terms.

Validate Inputs and Clamp Requests

The math only stays useful if the inputs are valid. Good pagination code checks for:

  • page size greater than zero
  • non-negative total item count
  • legal current page values

If a user requests page 99 but only 10 pages exist, many systems clamp the request to the last page or return an empty result with a clear error. The total-page calculation and the request-validation logic should be designed together.

Pagination and Database Queries

Page-count logic usually feeds directly into database offsets or API slices. That is why it is worth keeping the formulas together in one place: total pages tells you whether the requested page is valid, and the offset tells you where that page begins in the result set.

When those two calculations are implemented separately with different assumptions, pagination bugs tend to appear at the end of the dataset or around empty-result cases.

Common Pitfalls

Using truncating division instead of ceiling division undercounts the final partially filled page.

Allowing itemsPerPage to be zero creates a division error and usually points to missing validation.

Failing to define the zero-item behavior causes inconsistent API and UI behavior later.

Confusing total pages with query offset leads to bugs in database pagination or list slicing.

Ignoring out-of-range requested pages can produce negative offsets or empty data in confusing places.

Summary

  • Total pages should use ceiling division, not floor division.
  • 'Math.ceil(totalItems / itemsPerPage) is the direct and standard formula.'
  • Integer arithmetic can express the same idea with (total + perPage - 1) // perPage.
  • Decide explicitly how your system treats zero items.
  • Keep total-page calculation, offset logic, and page validation aligned.

Course illustration
Course illustration

All Rights Reserved.