Math.Round has been improved in C#.
Consider the below piece of code:

Console.WriteLine(Math.Round(10.4)); // Rounds to 10.0
Console.WriteLine(Math.Round(10.7)); // Rounds to 11.0
Console.WriteLine(Math.Round(10.5)); // Rounds to 10.0

There is nothing surprising about the first two statements.
In the third statement however, 10.5 is rounded to 10 not 11. C# provides for a way to specify how the middle point has to be treated.
A enumeration ‘MidpointRounding’ that defines how mid points are treated.

Console.WriteLine(Math.Round(10.5, MidpointRounding.AwayFromZero)); // Rounds to 11.
Console.WriteLine(Math.Round(10.5, MidpointRounding.ToEven)); // Rounds to 10.
Console.WriteLine(Math.Round(11.5)); //Rounds to 11.
Console.WriteLine(Math.Round(11.5, MidpointRounding.AwayFromZero)); // Rounds to 12.
Console.WriteLine(Math.Round(11.5, MidpointRounding.ToEven)); // Rounds to 12.

‘AwayFromZero’ – Rounds the number to the next highest value.
‘ToEven’ – Rounds the number to Even number.

So for a odd fraction, the default round will round it to the lesser number and any of the above overloads will take it to the Next number.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s