-1

Can someone explain to me why the below code outputs 1100 in both cases?

decimal toEven = 1100.5m;
decimal awayFromZero = 1099.5m;

Console.WriteLine(Math.Round(toEven)); // output 1100
Console.WriteLine(Math.Round(awayFromZero)); // output 1100

It looks like that Math.Round() changes MidpointRounding strategy after the number 1100. If you use Math.Round() on decimals under 1100 with a .5 decimal Math.Round() uses the AwayFromZero MidpointRounding by default. But if you use decimals over 1100 Math.Round() will use the ToEven MidpointRound by default. Why?

I know i can set the MidpointRounding my self to fix the problem. I'm just curious why Math.Round() works like this.

Poku
  • 3,138
  • 10
  • 46
  • 64

1 Answers1

3

I'm just curious why Math.Round() works like this.

Because that's the way it's designed and documented to behave:

If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned.

The behaviour doesn't change around 1100 either, Math.Round(1097.5m) and Math.Round(1098.5m) both return 1098 for example.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • I can see that i misunderstood the behavior of the to even term. Thanks for clarifying. – Poku Aug 09 '16 at 08:01