Primitive double value equal depends on magnitude?

后端 未结 3 1836
星月不相逢
星月不相逢 2020-12-29 17:05

I have to check to see whether two double values are equal including magnitude and precision. I encounter a weird scenario where primitive double equals check is not consist

3条回答
  •  有刺的猬
    2020-12-29 17:16

    Floating point numbers are approximations. They have a finite set of discrete values possible. When you create a floating point number by parsing a string, the closest possible floating point value is selected to represent it.

    The double closest to 15.999999999999999 is 15.999999999999998, not 16.0, so that comparison is unequal. But 17.0 is the closest double to 16.999999999999999, so they compare equal.

提交回复
热议问题