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

Viewed 37170

The following code in C# doesn't work:

int iValue = 0;
double dValue = 0.0;

bool isEqual = iValue.Equals(dValue);

So, the question: what's the best way to compare Double and Int?

7 Answers

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.

If you have not done any calculations using the double, you can just use ==. This is because an integer can be represented by a double exactly (only between -2^53 and 2^53).

int iValue = 0;
double dValue = 0.0;

bool isEqual = iValue == dValue;

This returns true.

The reason why Equals doesn't work is that the == operator will automatically convert the integer to a double before comparison, whereas Equals won't and thus fails.

This answer has more information: https://stackoverflow.com/a/52525223/15714398

If you have done calculations using the double, all bets are off and you have to do some analysis of the number of significant figures in your calculations.

Related