2

Possible Duplicate:
.Net Round Bug
In C#: Math.Round(2.5) result is 2 (instead of 3)! Are you kidding me?

Code:

var d1 = Math.Round(187.5); // 188
var d2 = Math.Round(62.5); // 62

Why is it so?

Community
  • 1
  • 1
Rookian
  • 19,841
  • 28
  • 110
  • 180

2 Answers2

17

By default, Math.Round uses a form of rounding called Banker's Rounding, which rounds to the nearest even integer when the input is halfway between two integers.

See Why does .NET use banker's rounding as default? for an understanding of this design decision.

If you don't like this behaviour, you can always use this overload of Math.Round, which lets you specify the MidPointRoundingMode (ToEven, AwayFromZero).

Community
  • 1
  • 1
Ani
  • 111,048
  • 26
  • 262
  • 307
  • @Joey: Please refrain from editing posts just after they have been posted, especially during the edit window. Thanks. – Ani Nov 01 '11 at 15:17
  • It's technically possible; the post was lacking in information and plenty of answers remain that way even after the edit window. You can either revert or override the changes which you did in this case anyway, so where was the harm in what I have done? – Joey Nov 01 '11 at 16:57
  • @Joey: You could wait for a while since there is a good chance that a post is being edited during the edit window. In this case, I didn't actually 'override' - it was actually a case of clashing edits. – Ani Nov 02 '11 at 02:42
2

You can change this behaviour with an call to this overload of the method - http://msdn.microsoft.com/en-us/library/ms131274.aspx

ClearCarbon
  • 459
  • 4
  • 13