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

前端 未结 6 2065
遥遥无期
遥遥无期 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:27

    Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.

    Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:

    if (Math.Abs(something) < 0.001)
    

    The epsilon you should use is application-specific - it depends on what you're doing.

    Of course, if the result should be exactly zero, then a simple equality check is fine.

提交回复
热议问题