Alex Rivera | Logout

Is it wrong to compare a double to 0 like this: doubleVariable==0?

Asked 2011-04-14T05:05:25.353
13

It is ok to do this?

double doubleVariable=0.0;
if (doubleVariable==0) {
   ...
}

Or this code would suffer from potential rounding problems?

Edit
Report

2 Answers

9

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: 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);
answered 2011-04-14T05:07:34.410
0

You should not use double for such comparision. double creates problem.
e.g double n1=0.55 double n2=100 then double ans=n1*n2 should be 55.0
but when you debug ans is 55.000000000000007. if(ans==55.0)
will fail. in such case you can face a problem.

answered 2011-04-14T05:19:45.367

Your Answer