I must be missing some subtlety of .NET rounding. So I am looking at this example:
decimal num = 2.5M;
var result = Math.Round(num);
Why is result = 2
? (I would have expected 3 since it should round up)
I must be missing some subtlety of .NET rounding. So I am looking at this example:
decimal num = 2.5M;
var result = Math.Round(num);
Why is result = 2
? (I would have expected 3 since it should round up)
See MSDN:
Decimal Math.Round(Decimald)
Rounds a decimal value to the nearest integer, and rounds midpoint values to the nearest even number (example).
"Midpoint" here means .5
; the even number in your case is 2
. If you rounded 3.5
this way, it would result in 4
.
If you want to use "away from zero" rounding instead, you can use the System.MidpointRounding.AwayFromZero
enum:
decimal d = 2.5M;
decimal roundedD = Math.Round(d, MidpointRounding.AwayFromZero); // results in 3
Regarding why it uses midpoint rounding (AKA "banker's rounding") by default instead of "away from zero" rounding, see this answer. Supposedly it's a better algorithm (i.e. more efficient over many iterations).
If you want classic rounding use
decimal num = 2.5M;
var result = Math.Round(num,0, MidpointRounding.AwayFromZero);
Please see https://msdn.microsoft.com/en-us/library/system.math.round(v=vs.110).aspx for details