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

前端 未结 6 1825
既然无缘
既然无缘 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:48

    This really depends on what you consider "equal". If you want your comparison to return true if and only if the double precisely matches the integer value (i.e. has no fractional component), you should cast your int to a double to do the comparison:

    bool isEqual = (double)iValue == dValue;
    

    If something like 1.1 would be considered equal to 1, you can either cast the double to an int (if you want to ignore the fractional component altogether) or round the double if you want say 1.9 to equal 2.

提交回复
热议问题