Search code examples
c#integernumbersfloatingmath.round

Why does Math.Round give me two different values?


class Program {
    static void Main(string[] args) {
      double d = 120.5;
      Console.WriteLine(Math.Round(120.5)); //121
      Console.WriteLine(Math.Round(d)); // 120
    }
}

When a variable is passed as an argument into Math.Round it produces an answer similar to Convert.ToInt32 where floating numbers are rounded off to the nearest even number if the trailing tenth number is 0.5.

Anyone can kindly explain? Thanks in advance.

Thanks for the answers! I use Replit most of the time, that's the output I got. But seeing the replies, I tested it again in VS and I got both 120. I guess there's a bug in replit? Kindly refer to attachments.

enter image description here

enter image description here


Solution

  • I tested your code and returns 120 in two modes. It is good to know that the Math.Round() has features that you can use.

    For example, you can say to always round to a number that is further from zero:

     double d = 120.5;
    
     Console.WriteLine(Math.Round(d,MidpointRounding.AwayFromZero)); //always 121
    

    or final digit is even:

     Console.WriteLine(Math.Round(d,MidpointRounding.ToEven)); //always 120
    

    and other features like MidpointRounding.ToNegativeInfinity, MidpointRounding.ToPositiveInfinity ....