• Home
  • About Me
  • Musings
  • Programming
  • Open Source
  • Computers
  • Society
  • Books
  • Design
  • Movies
  • Math.Round

    Posted on February 28th, 2009 by Rajeshwaran S P

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

    1
    2
    3
    
    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.

    1
    2
    3
    4
    5
    
    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.

    Possibly Related posts:

    1. Implicit Variable in C# 2008 C# 2008 allows for creating implicit variables using the ‘var’...
    2. C#: Null coalescing operator C# has a ?? operator, which is called the ‘Null...
    3. One more step forward Another year has passed, I have added one more step...
    4. C#: Calculate Age in Years, Month and Days Today I was given the task of finding the age...

    Tags: ,

    Leave a Reply