在java中int类型比较可以用“==”,而double类型的数据不能用“= =”比较,否则得到永不相等的结果。
一般可以Double的doubleToLongBits()方法将其转换为long类型从而比较两个Double类型的数据大小。
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)
}
//0表示d1=d2,1表示d1大于d2, -1表示d1<d2