A simple question about Math.Round in C #

Say I have an int that represents the number of rows in a collection, and I want to determine the number of pages needed to store the collection for a specific page size.

So, if I have a page size of 20 and a collection size of 89, I need 5 pages.

How does the Math.Round function work to get what I need? I need to round to the next integer, not the closest.

Thanks for your suggestions.

+3
source share
4 answers

You do not want to use Math.Round () at all. You should use Math.Ceiling (), which will return the smallest integer value greater than the double passed to:

var pageSize = 20D;
var pages = Math.Ceiling(collection.Count() / pageSize);
+11
source

Math.Ceiling () is what you are looking for, I believe.

+4
source
+3

You can do doubles and use Math.Ceiling, as others have stated. But why? You can completely do this job in integer arithmetic.

However, as you will see if you read all the fun comments to all the answers here, sometimes you need to try five or six times before you get the code correctly.

How can I guarantee that the separation of integers is always rounded?

+3
source

All Articles