Double型比较大小 compareTo()

2023-11-08

 

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

 

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Double型比较大小 compareTo() 的相关文章

随机推荐