【问题标题】:Java :: comparing ronded doubles doesn't workJava :: 比较 ronded 双打不起作用
【发布时间】:2020-04-10 08:44:51
【问题描述】:

我想比较两个数字:

  • -3.123
  • -3.123456

我将使用double 来存储它们,我只想考虑前 3 位小数,所以:

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class DecimalComparator {
    public static void main(String[] args) {
        areEqualByThreeDecimalPlaces(-3.123, -3.123456);
    }

    public static boolean areEqualByThreeDecimalPlaces (double one, double two) {
        boolean same = true;

        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.FLOOR);
        System.out.println(df.format(one));
        System.out.println(df.format(two));

        if (df.format(one).equals(df.format(two))) {
            same = true;
            System.out.println("true");
        } else {
            same = false;
            System.out.println("false");
        }
        return same;
    }
}

代码返回我:

-3.123
-3.124
false

为什么第二个数字四舍五入为 -3.124?

【问题讨论】:

  • Ni @Mureinik,我检查了 '.equals()' 但结果相同
  • 在这里使用== 肯定是错误的,但我看到您已将您的帖子更正为使用equals,所以我重新打开了它。请参阅下面的my answer,了解您当前面临的问题。

标签: java boolean compare double decimal


【解决方案1】:
Hi its just that when u round off 3.123456 it works the below way when decimal 
places are reduced :

 3.12346
 3.1235
 3.124
 3.12
 3.1 

//commenting the set rounding mode will make it work the way u want.
public static void main (String[] args ) {
        double one =-3.123;
         double two = -3.123456;
        boolean same = true;

        DecimalFormat df = new DecimalFormat("#.###");
        //remove this line
        //df.setRoundingMode(RoundingMode.FLOOR);

        System.out.println(df.format(one));
        System.out.println(df.format(two));

        if (df.format(one).equals(df.format(two))) {
            same = true;
            System.out.println("true");
        } else {
            same = false;
            System.out.println("false");
        }
        System.out.println(same);
    }

【讨论】:

    【解决方案2】:

    RoundingMode.FLOOR 将数字向下舍入 - 您的代码适用于正数,但不适用于负数。您需要使用 RoundingMode.DOWN 来删除 N 个位置之后的数字:

    df.setRoundingMode(RoundingMode.DOWN);
    // Here ------------------------^
    

    【讨论】:

    • 谢谢@Mureinik,但是如何让它同时适用于正数和负数?
    • @FrancescoMantovani 如果不清楚,我的意思是使用FLOOR,就像你在问题中所做的那样,只适用于正数。正如我在回答中所做的那样,使用RoundingMode.DOWN 对正面和负面都有效。
    猜你喜欢
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2015-01-12
    • 1970-01-01
    相关资源
    最近更新 更多