comparison of floating point numbers with equality operator. possible loss of precision while rounding values

double值由外部传入

        private void Compare(double value)
        {
            string text;
            if (value != 0) //小数位后保留2位
            {
                //小数点后保留2位小数
                text = string.Format("{0:0.00}", value);
            }
            else
            {
                text = "0";
            }
        }

http://*.com/questions/5658799/is-it-wrong-to-compare-a-double-to-0-like-this-doublevariable-0

Nope it's perfectly legal if you are only going to compare against 0 as the right side of comparison will automatically casted to double. On the other hand, it would yield all the round-off errors if you where to compare against == 0.10000001

You are better or reading the discussion about float to 0 comparison here: C#.NET: Is it safe to check floating point values for equality to 0?

Also this discussion is very informative about weird precision problems on floats: Why the result is different for this problem?

i.e. below will yield false:

double d1 = 1.000001; double d2 =0.000001;
Console.WriteLine((d1-d2)==1.0);

http://*.com/questions/485175/is-it-safe-to-check-floating-point-values-for-equality-to-0-in-c-net

It is safe to expect that the comparison will return true if and only if the double variable has a value of exactly 0.0 (which in your original code snippet is, of course, the case). This is consistent with the semantics of the == operator. a == b means "a is equal to b".

It is not safe (because it is not correct) to expect that the result of some calculation will be zero in double (or, more generally, floating point) arithmetics whenever the result of the same calculation in pure Mathematics is zero. This is because when calculations come into the ground, floating point precision error appears - a concept which, needless to say, does not exist in Real number arithmetics in Mathematics.

http://*.com/questions/6598179/the-right-way-to-compare-a-system-double-to-0-a-number-int

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.