Smartboy
Smartboy

Reputation: 1006

How to always get a whole number if we divide two integers in c#

I have three integer type variable

  1. Totallistcount
  2. totalpagescount
  3. 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 in totalpagescount but I need 2 in totalpagescount , because 9 items on the first page and rest of item will be displayed on last page , How can I do this

Thanks ,

Upvotes: 5

Views: 26010

Answers (4)

jug
jug

Reputation: 451

an other solution :

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

int pageCount = (14 - 1) / 9 + 1; => pagecount = 2

Upvotes: 1

Vyktor
Vyktor

Reputation: 20997

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);

Upvotes: 5

Rawling
Rawling

Reputation: 50104

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;

Upvotes: 3

dtb
dtb

Reputation: 217233

totalpagescount = (Totallistcount + perpagecount - 1) / perpagecount ;

Upvotes: 17

Related Questions