39

I'm using a react component that need me to pass in below prop

<Pager 
      totalPages={10}
      currentPage={1}
/>

I can't figure out the calculation as in the api I have total_items, not totalPages. if I have 50 total_items, how can I produce 5 for the totalPages prop? says my limit is 10.

fubar
  • 16,918
  • 4
  • 37
  • 43
Cecilia Chan
  • 679
  • 2
  • 8
  • 17

3 Answers3

125

Divide total_items by limit, and round the value up.

Math.ceil(total_items/limit);

50 items / 10 per page = 5 pages
55 items / 10 per page = 6 pages
fubar
  • 16,918
  • 4
  • 37
  • 43
0

integer only calculation:

int total_pages = total_items==0 ? 0 : (total_items - 1) / page_size + 1;
-6

you need to check if there is a quotient from the divide operation because there is apparently few items need to be showed in another page

for example:

6 items
5 limit

if we just divide and ceil we will get 1 which is incorrect because there is one item need an extra page to be counted

totalPages_pre = (total_items/limit)
totalPages = (search.total % page_size) == 0 ? totalPages_pre : totalPages_pre + 1
Umair
  • 6,366
  • 15
  • 42
  • 50
Ashraf
  • 9
  • 1
  • 1
    `Math.ceil()` does give higher number (2 in this case). – Bogac Jun 03 '18 at 06:06
  • This statement is actually correct "if we just divide and ceil we will get 1", this is caused by java's integer arithmetic, Math.ceil expects a double but dividing `integer / integer` returns `integer` – emont01 Jun 28 '21 at 03:24