What is the correct way to round to integers?

I am dividing 2 integers and want to get an integer as a result. I want the correct Math.Round() method, so when I share, it is always rounded to the next integer, no matter how. Here are some examples with the expectations below.

 int result = (6/4); // = 2 int result = (3/4); // = 1 int result = (1/4); // = 1 int result = (8/4); // = 2 int result = (9/4); // = 3 

What is the right way to do this?

+4
source share
4 answers

Since all the integers in your example are positive, I assume that you are not interested in the case when one or both operands are negative or zero.

Math.Round works with floating point numbers. There is no need.

Separating two integers gives an integer result. It is always rounded. You want something like this:

 int Divide(int numerator, int denominator) { return (numerator + denominator - 1) / denominator; } 

For example, for 1/4 we get (1 + 4 - 1) / 4 = 4 / 4 = 1 , and for 8/4 we get (8 + 4 - 1) / 4 = 11 / 4 = 2 .

There is very little possibility of overflow, therefore, if the numerator is always greater than zero, it is better to use:

 int Divide(int numerator, int denominator) { return 1 + (numerator - 1) / denominator; } 
+6
source

You need to do the division as float / double and use Math.Ceiling :

Math.Ceiling ... Returns the smallest integer value that is greater than or equal to the specified double-precision floating-point number.

Example:

  int result = (int)Math.Ceiling(6/4.0); result = (int)Math.Ceiling((double)3/4); 
+4
source

One of these integers must be double :

 double result = (6d/4); // 1.5 int rounded = (int)Math.Round(result, MidpointRounding.AwayFromZero); 
0
source

This is definitely not the method you are looking for ...

 int mod = 9 % 4; int result = (9 - mod) / 4) + (mod > 0 ? 1 : 0); 

Does not require casting or using the Math class.

0
source

All Articles