Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to round dividing to integers?

Tags:

c#

math

I am dividing 2 integers and looking to get an integer as a result. I want the right Math.Round() method so when I divide, it always round to the next integer regardless of how. Here are a bunch of examples with 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 correct way of doing this?

like image 757
leora Avatar asked Dec 21 '22 09:12

leora


1 Answers

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

Math.Round works on floating-point numbers. That is not necessary here.

Dividing two integers gives an integer result. It always rounds down. 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's a very slight possibility of overflow here, so if the numerator is always greater than zero, it's better to use:

int Divide(int numerator, int denominator) {
    return 1 + (numerator - 1) / denominator;
}
like image 86
Jeffrey Sax Avatar answered Jan 08 '23 13:01

Jeffrey Sax