Java:检查两个双精度值是否匹配特定的小数位

2022-09-04 05:18:05

比较这两个值将得到“true”:

53.9173333333333  53.9173

答案 1

如果你想要并被认定为平等:a = 1.00001b = 0.99999

return Math.abs(a - b) < 1e-4;

否则,如果你想要并被认定为平等,并且两者都是积极的,而不是巨大的:a = 1.00010b = 1.00019ab

return Math.floor(a * 10000) == Math.floor(b * 10000);
// compare by == is fine here because both sides are integral values.
// double can represent integral values below 2**53 exactly.

否则,请使用 Java 中是否有任何用于截断双精度值的函数中所示的方法:truncate

BigDecimal aa = new BigDecimal(a);
BigDecimal bb = new BigDecimal(b);
aa = aa.setScale(4, BigDecimal.ROUND_DOWN);
bb = bb.setScale(4, BigDecimal.ROUND_DOWN);
return aa.equals(bb);

答案 2

这是一个简单的例子,如果你仍然需要这个:)

public static boolean areEqualByThreeDecimalPlaces(double a, double b) {

    a = a * 1000;

    b = b * 1000;

    int a1 = (int) a;

    int b1 = (int) b;

    if (a1 == b1) {
        System.out.println("it works");
        return true;
    }

    else
        System.out.println("it doesn't work");
    return false;

推荐