PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 17, 2022

[FIXED] Why does Math.Round give me two different values?

 October 17, 2022     c#, floating, integer, math.round, numbers     No comments   

Issue

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 ....



Answered By - hossein sabziani
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing