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

后端 未结 6 777
夕颜
夕颜 2021-01-04 04:57

It is ok to do this?

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

Or this code would suffer from potential rounding problem

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 05:45

    What you have there is 0, which is an integer literal. It is implicitly converted to a double which you could represent with the double literal 0.0 (implicit conversion). Then there is a comparison between the two doubles. A rounding error could cause doubleVariable to not be equal to 0.0 (by some other math you might do, not just setting it), but there could never be a rounding error when converting the integer 0 to double. The code you have there is totally safe, but I would favor == 0.0 instead.

提交回复
热议问题