关于 Double.compare()
使用<
和>
对浮点数进行比较时,不够严谨,有这两个问题:0.0、-0.0的比较问题(0.0 > -0.0),以及NaN的问题(NaN永远比!NaN大),建议使用Double.compare()
或Float.compare()
进行比较。
Double.compare()源码
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use doubleToRawLongBits because of possibility of NaNs.
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
源码中将浮点数转化为long类型的位序列,并根据IEEE754标准进行大小比较,可以解决这两个问题。