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

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

    You really can't compare floating point and integral values in a naive way; particularly, since there's the classic floating point representation challenges. What you can do is subtract one from the other and see if the difference between them is less than some precision you care about, like so:

    int iValue = 0;
    double dValue = 0.0;
    
    var diff = Math.Abs(dvalue - iValue);
    if( diff < 0.0000001 ) // need some min threshold to compare floating points
       return true; // items equal
    

    You really have to define for yourself what equality means to you. For example, you may want a floating point value to round towards the nearest integer, so that 3.999999981 will be "equal" to 4. Or you may want to truncate the value, so it would effectively be 3. It all depends on what you're trying to achieve.

    EDIT: Note that i chose 0.0000001 as an example threshold value ... you need to decide for yourself what precision is sufficient for comparison. Just realize you need to be within the normal representational bounds of double which I believe is defined as Double.Epsilon.

提交回复
热议问题