How to always get a whole number if we divide two integers in c#
20,299
Solution 1
totalpagescount = (Totallistcount + perpagecount - 1) / perpagecount ;
Solution 2
This is how integer division should work, you need to convert it to double
first to be able to get the number and then use Ceiling
to "round it up":
(int)Math.Ceiling( (double)Totallistcount / perpagecount);
Solution 3
If you want to round up, you need to perform the division as a floating point number, then call Math.Ceiling
to get the next-highest whole number.
double quotient = Totallistcount / (double)perpagecount;
double ceiling = Math.Ceiling(quotient);
int totalpagescount = (int)ceiling;
Solution 4
an other solution :
int pageCount = (records - 1) / recordsPerPage + 1;
int pageCount = (14 - 1) / 9 + 1; => pagecount = 2
Author by
Smartboy
Updated on July 05, 2022Comments
-
Smartboy almost 2 years
I have three integer type variable
- Totallistcount
- totalpagescount
- perpagecount
Suppose at initial level i have this
Totallistcount = 14; perpagecount = 9;
Now I have a formula to found total number of pages possible
totalpagescount = Totallistcount / perpagecount ;
but in this situtation I got
1
intotalpagescount
but I need2
intotalpagescount
, because 9 items on the first page and rest of item will be displayed on last page , How can I do thisThanks ,
-
Rawling over 11 yearsHeh... I thought of adding the page count, realised it would break when the total count was already a multiple, and went "meh" instead of trying to figure it out properly.
-
Vyktor over 11 years+1 This is brilliant an idea, I've never though about it in this way... I'm curious though... What would be the performance difference between this solution and using
Ceiling
-like-solution.