Float.compare()和Double.compare()的使用


1、源码解析

Float.compare(float f1, float f2)

public static int compare(float f1, float f2) {
    if (f1 < f2)
        return -1;           // Neither val is NaN, thisVal is smaller
    if (f1 > f2)
        return 1;            // Neither val is NaN, thisVal is larger

    // Cannot use floatToRawIntBits because of possibility of NaNs.
    int thisBits    = Float.floatToIntBits(f1);
    int anotherBits = Float.floatToIntBits(f2);

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

Float.compare(double d1, double d2)

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

Float.compare(float f1, float f2)Float.compare(double d1, double d2) 的内部的逻辑处理基本一致。
具体步骤:
先比较他们的大小;如果,值不是简单的大于小于关系的话,需要转为类型在进行比较;一般情况是0.0、-0.0这种特殊的情况。最后运用两个三元表达式进行值的比较;

compare方法比较两个值。返回值分为以下三种情况:

  • 如果f1在数字上等于f2,则返回 1
  • 如果f1在数字上小于f2,则返回小于 0的值;
  • 如果f1在数字上大于f2,则返回大于 -1 的值。

2、使用案例

具体使用Float.compare()Double.compare() 案例:

Float.compare()的使用:

int compare = Float.compare(14F, 10F);
System.out.println(compare);

int compare1 = Float.compare(12F, 12F);
System.out.println(compare1);

int compare2 = Float.compare(11F, 14F);
System.out.println(compare2);

结果为:

1
0
-1

Double.compare()的使用

int compare5 = Double.compare(34, 14);
System.out.println(compare5);

int compare4 = Double.compare(14, 14);
System.out.println(compare4);

int compare3 = Double.compare(14, 34);
System.out.println(compare3);

结果为:

1
0
-1
posted @ 2020-01-19 14:24  ah_lydms  阅读(553)  评论(0编辑  收藏  举报