前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Float.compare()和Double.compare()的使用

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

作者头像
ha_lydms
发布2023-08-09 20:56:20
1850
发布2023-08-09 20:56:20
举报
文章被收录于专栏:学习内容学习内容

1、源码解析

Float.compare(float f1, float f2)

代码语言:javascript
复制
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)

代码语言:javascript
复制
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()的使用:

代码语言:javascript
复制
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);

结果为:

代码语言:javascript
复制
1
0
-1

Double.compare()的使用

代码语言:javascript
复制
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);

结果为:

代码语言:javascript
复制
1
0
-1
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、源码解析
  • 2、使用案例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档