The right way to compare a System.Double to '0' (a number, int?)

前端 未结 6 2089
遥遥无期
遥遥无期 2020-12-08 03:44

Sorry, this might be a easy stupid question, but I need to know to be sure.

I have this if expression,

void Foo()
{
    System.Double so         


        
6条回答
  •  误落风尘
    2020-12-08 04:04

    Here is the example presenting the problem (prepared in LinQPad - if you don't have it just use Console.Writeline instead of Dump method):

    void Main()
    {
        double x = 0.000001 / 0.1;
        double y = 0.001 * 0.01; 
    
        double res = (x-y);
        res.Dump();
        (res == 0).Dump();
    }
    

    Both x and y are theoretically same and equal to: 0.00001 but because of lack of "infinite precision" those values are slightly different. Unfortunately slightly enough to return false when comparing to 0 in usual way.

提交回复
热议问题