I am working on developing custom pager control to my grid view.
I am using the following syntax to get no of pages:
dblpagecount = (doble)(totrecords / grdPages.PageSize);
pagecount = (int)Math.Ceiling(dblPagecount);
Using above syntax , if the no of records is 41 and page size is 5 then I am getting pagecount as 8 which should be 9.
If I use the below syntax,
double dblPagecount = (double)((decimal)totrecords /grdPages.PageSize);
pagecount = (int)Math.Ceiling(dblPagecount);
I am getting exact page count i.e 9
I got the desired result , but unable to understand why the above synatax is not giving desired results.
When I debugged in first case, I observed that dblpagecount is getting result as 8.0 insted of 8.2
Can any one please clarify , how the above statements works ?
I'm assuming that both totrecords
and grdPages.PageSize
are of type int
. Therefore, regardless of the type of dblpagecount
, you'll end up with the division being performed in integer arithmetic, which truncates towards 0. However, I wouldn't actually use your second piece of code (and certainly wouldn't use both double
and decimal
- mixing those is almost always a bad idea). Instead, I'd just use:
// Names changes slightly for readability
int pageCount = (totalRecords + grdPages.PageSize - 1) / grdPages.PageSize;
This will effectively "round up" without ever requiring any floating point operations.
See more on this question at Stackoverflow