The simplest formula to calculate page count?
-
05-07-2019 - |
Question
I have an array and I want to divide them into page according to preset page size.
This is how I do:
private int CalcPagesCount()
{
int totalPage = imagesFound.Length / PageSize;
// add the last page, ugly
if (imagesFound.Length % PageSize != 0) totalPage++;
return totalPage;
}
I feel the calculation is not the simplest (I am poor in math), can you give one simpler calculation formula?
Solution
Force it to round up:
totalPage = (imagesFound.Length + PageSize - 1) / PageSize;
Or use floating point math:
totalPage = (int) Math.Ceiling((double) imagesFound.Length / PageSize);
OTHER TIPS
Actually, you are close to the best you can do. About the only thing that I can think of that might be "better" is something like this:
totalPage = (imagesFound.Length + PageSize - 1) / PageSize;
And the only reason that this is any better is that you avoid the if statement.
NOTE: you will always get at least 1 page, even for 0 count, if the page size is > 1, which is what I needed but may not be what you need. A page size of 1(silly but technically valid) and a count of 0 would be zero pages. Depending on your needs you may want to check for a zero value for count & page size of 1
int pages = ((count - 1) / PAGESIZE) + 1;
The OP contains a valid answer. If I wanted to turn off paging then I could set PageSize = int.MaxValue
.
Several answers here add to PageSize
(imagesFound.Length + PageSize
) and that would cause an overflow. Which then leads to an incorrect result.
This is the code I am going to use:
int imageCount = imagesFound.Length;
// include this if when you always want at least 1 page
if (imageCount == 0)
{
return 1;
}
return imageCount % PageSize != 0
? imageCount / PageSize + 1
: imageCount / PageSize;
To avoid having errors with page numbering the best way I can think of calculating noOfPages is by doing the following line
totalPage = Math.Ceiling(imagesFound.Length / PageSize);
This should not give you page 2 when PageSize == imagesFound.Length