1
votes

When I used Math.Round() function in C#, I did not understand why C# sets MidpointRounding.ToEven as the default type.

double number = Math.Round(1.625, 2); // number = 1.62

I checked the C# tool book and found that Math.Round() have two types. One is MidpointRounding.ToEven and the other one is MidpointRounding.AwayFromZero. The Math.Round() has the default type as MidpointRounding.ToEven. So, I got two ways to set the number value to follow the regular math logic.

double number = Math.Round(1.625, 2, MidpointRounding.AwayFromZero); // number = 1.63

Or

double number = 1.625;
string stringNumber = number.ToString("N2"); // stringNumber = "1.63"

My question is why C# sets MidpointRounding.ToEven as the default type, but the ToString("N2") would round numbers with regular math logic. What circumstances would we use MidpointRounding.ToEven? Please let me know if I used the Math.Round() in an incorrect way.

Its not clear what you are askig. You have discovered the behavior of Math.Round and found that it does what the docs say it does. You are surprised that ToString uses a different overload of Math.Round. Interesting I agree, but whats the questionpm100