Click here to Skip to main content
15,907,395 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Decimal d = 4.0m / 3.0m;            //same problem in Double
            Console.Write((4m / d) == (3m));    //same problem in this code Console.Write((4m / d).Equals(3m));
            Console.ReadLine();
            //expected output : True
            //actual output : False
        }
    }
}


I don't know how to solve this problem. Does anyone know how to solve it?
Posted

Try changing your comparison to Math.Round(4m/d, 27) == 3.
 
Share this answer
 
you must use rounding
C#
static void Main(string[] args)
        {
            Decimal d = 4.0m / 3.0m;
            Console.Write(System.Math.Round((4m / d),2) == (3m));
            Console.ReadLine();
        }
 
Share this answer
 
You're dealing with decimals here
Just round off your final result before comparing

Console.Write(Math.Round((4m / d), 2, MidpointRounding.AwayFromZero) == (3m));

remember, its not a good idea to round off at every point of your calculation (or even when storing it for that matter). Round off when considering it (for display or comparison)

Hope this is what y'r looking for
 
Share this answer
 
C#
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Decimal d = 4.0m / 3.0m;            //same problem in Double
            Console.Write((4m / d) == (3m));    //same problem in this code Console.Write((4m / d).Equals(3m));
            Console.ReadLine();
            //expected output : True
            //actual output : False
        }
    }
}

I underlined your error. It should be:
//expected output : False

And now everything is ok.
Or, maybe, you should learn some concepts first. Try here[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900