The simplest formula to calculate page count?

Benny picture Benny · Oct 23, 2009 · Viewed 72k times · Source

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?

Answer

John Kugelman picture John Kugelman · Oct 23, 2009

Force it to round up:

totalPage = (imagesFound.Length + PageSize - 1) / PageSize;

Or use floating point math:

totalPage = (int) Math.Ceiling((double) imagesFound.Length / PageSize);