user3124306 user3124306 - 1 year ago 93
C# Question

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:


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?

Answer Source

When performing integer division (by which we mean both arguments are integral types) C# 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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download