-1

I was just surfing some coding problems in C#. fiddle link here

Q: What is the output of the following code?

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Math.Round(6.5));
        Console.WriteLine(Math.Round(11.5));
    }
}

6 12

This is the output.

My doubt is if 6.5 comes as 6. How come 11.5 as 12?

It should be 11 or either 6.5 should be 7.

Maybe it is very unwise, Any suggestion/explanation helps me to understand clearly.

Jeya Suriya Muthumari
  • 1,947
  • 3
  • 25
  • 47
  • You should probably read how rounding function round the result: [here](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.7.2#System_Math_Round_System_Double_) and [here](https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=netframework-4.7.2). Default rounding method is `MidpointRounding.ToEven` _(therefore the result you get, are correct)_. – Julo Sep 23 '18 at 17:43
  • 3
    in situations like this the first thing you should is [RTFM](https://en.wikipedia.org/wiki/RTFM) – Selman Genç Sep 23 '18 at 17:44

1 Answers1

5

The documentation clearly defines this behaviour:

The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.

If you want to change this behaviour then use the overload that allows you to specify the mid point rounding behaviour (see docs).

Math.Round(6.5, MidpointRounding.AwayFromZero) // returns 7.
Chris
  • 27,210
  • 6
  • 71
  • 92