Java: Check if two double values match on specific no of decimal places

北慕城南 提交于 2019-12-22 04:49:20

问题


Comparing those two values shall result in a "true":

53.9173333333333  53.9173

回答1:


If you want a = 1.00001 and b = 0.99999 be identified as equal:

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

Otherwise, if you want a = 1.00010 and b = 1.00019 be identified as equal, and both a and b are positive and not huge:

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.

Otherwise, use the truncate method as shown in Are there any functions for truncating a double in java?:

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:


here is the simple example if you still need this :)

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;



回答3:


Naively:

if(Math.abs(a-b) < 0.0001)

However, that's not going to work correctly for all values. It's actually impossible to get it to work as long as you're using double, because double is implemented as binary fractons and does not even have decimal places.

You'll have to convert your values to String or BigDecimal to make meaningful tests about their decimal places.

You may want to read the Floating-Point Guide to improve your understanding of how floating point values work.




回答4:


Apache commons has this: org.apache.commons.math3.util.Precision equals(double x, double y, double eps)

epsilon would be the distance you would allow. Looks like yours would be 1e-5?

The source-code of this method looks like it uses Math.abs as suggested in other answers.




回答5:


Thanks. I did it this way:

double lon = 23.567889;
BigDecimal bdLon = new BigDecimal(lon);
bdLon = bdLon.setScale(4, BigDecimal.ROUND_HALF_UP);

System.out.println(bdLon.doubleValue());


来源:https://stackoverflow.com/questions/2944344/java-check-if-two-double-values-match-on-specific-no-of-decimal-places

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!