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
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ha_lydms

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值