Double型比較大小 compareTo()

 

public class DoubleCompare {

    public static void main(String[] args) {
        Double d1 = 100.0;
        Double d2 = 90.0;
        Double d3 = 150.005;
        int i = 10;

        System.out.println(d1.compareTo(d1));  // 0  即=0  d1=d1
        System.out.println(d1.compareTo(d2));  // 1  即>0  d1>d2
        System.out.println(d1.compareTo(d3));  // -1 即<0  d1<d3
    }

}

0
1
-1

 

compareTo()源碼:

    public int compareTo(Double anotherDouble) {
        return Double.compare(value, anotherDouble.value);
    }



    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)
    }

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章