simple question on Math.Round in C#
Let's say I have an int that represents the number of rows in a collection and I want to determine t开发者_高级运维he number of pages needed to hold the collection give a certain 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 nearest.
Thanks for your suggestions.
You don't want to use Math.Round() at all. You should be using Math.Ceiling() which will return the smallest integer value that is greater than the double passed in:
var pageSize = 20D;
var pages = Math.Ceiling(collection.Count() / pageSize);
Math.Ceiling() is what you are looking for I believe.
Use ceiling: Math.Ceiling
You can do the work in doubles and use Math.Ceiling, as others have stated. But why? You can do this work entirely in integer arithmetic.
However, as you'll see if you read all the hilarious comments to all the answers here, sometimes you have to try five or six times before you get the code right.
How can I ensure that a division of integers is always rounded up?
精彩评论