What's the best way to compare Double and Int?

前端 未结 6 1833
既然无缘
既然无缘 2020-11-29 10:43

The following code in C# doesn\'t work:

int iValue = 0;
double dValue = 0.0;

bool isEqual = iValue.Equals(dValue);

So, the question: what\

6条回答
  •  一个人的身影
    2020-11-29 11:23

    Nowadays, just about the only time one should be comparing values of types double and either integer or long for strict equality is when, for some reason, one is stuck storing or passing integral quantities as floating-point values and later needs to convert them back. Such conversion may in most cases be most easily accomplished by casting the integral type to double, and then comparing the result of that cast. Note that conversion from long to double may be imprecise if the number is outside the range ±252. Nonetheless, in the days before 64-bit long became available, double was a handy storage type for integer quantities which were too big for a 32-bit int but small enough to be handled by double.

    Note that converting a long to double and then doing the comparison will yield an "equal" result if the nominal value of the double doesn't precisely match the long value, but represents the closest possible double to that value. This behavior makes sense if one recognizes that floating-point types don't actually represent a single precise value, but rather a range of values.

提交回复
热议问题