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

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

    It's an exceedingly bad idea to compare integers and floating-point numbers for equality in any language. It works for very simple cases, but after you do any math at all, the likliehood of the program doing what you want it to decreases dramatically.

    It has to do with the way floating-point numbers are stored on a binary, digital system.

    If you are very sure you want to use this, create a class to make you own number with fractions. use one int to maintain the whole number, and another int to maintain the fraction.

提交回复
热议问题