C#: Pagination, Math.Ceiling
I'm creating some pagination and I'm getting an issue开发者_开发技巧.
If I have a number 12 and I want to divide that by 5 (5 is the number of results I want on a page), how would I round it up properly? This doesn't work:
int total = 12;
int pages = Math.Ceiling(12 / 5);
//pages = 2.4... but I need it to be 3
Even though your code should work, Math.Round
is wrong though, you could try this:
int pages = (total + pageSize - 1)/pageSize;
That should be the same as Math.Ceiling
except that you are always dealing with int
and not double
at any point as Math.Ceiling
returns.
EDIT: To get your code to work you could try:
int pages = (int)Math.Ceiling((double)12/(double)5);
But you should use the first example.
you could do:
int numPages = Math.Ceiling((decimal)12 / (decimal)5);
or
int numPages = (12 + 4) / 5; //(total + (perPage - 1)) / perPage
精彩评论