'Why does C# round (100-1)/2 to 49 instead of 50?

According to my calculator: (100-1) / 2 = 49.5

If I have an int like this:

int mid = (100 - 1) / 2

And printing mid will give me:

49

Why will C# give me 49 instead of 50? Aren't you supposed to round to the next whole number if it is .5 so that the number would be 50?



Solution 1:[1]

When performing integer division (by which we mean both arguments are integral types) the CLR will truncate the result; effectively rounding down for positive results.

If you want "standard" or midpoint rounding, you need to explicitly use Math.Round and floating point division (at least one argument is float, double or decimal).

Solution 2:[2]

This isn't rounding but integer arithmetic which truncates the floating point number, so

(100 - 1) / 2 == 99 / 2 = 49.5 which truncates to 49

and

(100 - 1) / -2 = 99 / -2 = -49.5 which truncates to -49

If you want real rounding then you must make at least one of the variables a floating point value and then call Math.Round on the result.

Solution 3:[3]

As others mentioned, integer division will truncate. This makes sense since 99 % 2 == 1 and you would expect that subtracting the modulus from the original value wouldn't change the division result, i.e. (99/2 == (99-(99%2))/2), so 99/2 = 98/2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ChrisF
Solution 3 KMoussa