3

Let's 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 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.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • possible duplicate of [How can I ensure that a division of integers is always rounded up?](http://stackoverflow.com/questions/921180/how-can-i-ensure-that-a-division-of-integers-is-always-rounded-up) – Eric Lippert Jun 09 '11 at 19:50
  • I don't think this is a duplicate. The OP's request is much simpler; he doesn't care about excess casting. – Brian Jun 10 '11 at 14:46

4 Answers4

11

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);
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • Ah ok, Math.Ceiling! It's showing: Error 10 The call is ambiguous between the following methods or properties: 'System.Math.Ceiling(decimal)' and 'System.Math.Ceiling(double)' – frenchie Jun 09 '11 at 18:54
  • @frenchie - Did you catch my update? Make sure you specify pageSize as a double. That will resolve the issue. – Justin Niessner Jun 09 '11 at 18:55
  • Small correction: `Math.Ceiling()` returns the smallest integer value that is greater than *or equal to* the value passed in (which is of course the correct behavior for the OP's requirement). It's also worth noting that the integer value returned by `Math.Ceiling()` is not of an integral type: it is either `double` or `decimal`, depending on which overload is called. – phoog Dec 30 '11 at 19:46
4

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

mrK
  • 2,208
  • 4
  • 32
  • 46
3

Use ceiling: Math.Ceiling

Candide
  • 30,469
  • 8
  • 53
  • 60
3

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?

Community
  • 1
  • 1
Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • 1
    Using `Math.Ceiling` on a `double` results in short, familiar, easy-to-read code. I doubt the use of `double` introduce a performance bottleneck. I think avoiding floating point arithmetic only serves to complicate the solution. – Brian Jun 10 '11 at 14:53