Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare BigDecimal, but approximately?

Tags:

java

android

I have this code:

BigDecimal d = ...;
if (d.compareTo(Expression.PI) == 0) {
    //do something
}

where Expression.PI is pi rounded to 100th decimal.

But I don't need to compare if d is equal to pi with up to 100 decimals, but only let's say up to 20th decimal. To put it other way, how to check if d is approximately equal to pi?

I tried

Expression.PI.setScale(20, RoundingMode.HALF_UP).compareTo(d.setScale(20, RoundingMode.HALF_UP)) == 0;

and

Expression.PI.setScale(20, RoundingMode.HALF_UP).compareTo(d) == 0;

But none of these two seem to work. What am I doing wrong here?

like image 834
leonz Avatar asked Sep 13 '25 11:09

leonz


2 Answers

As lucasvw mentioned in the comments, I think you're already doing it correctly and there must be a problem with your 'd' value. Here is a test class that shows the correct result.

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalTest {

public static void main(String args[]) {
    BigDecimal PI = new BigDecimal("3.14159265358979323846264338327950288419");
    BigDecimal otherValue = new BigDecimal("3.14159");

    boolean test = PI.setScale(5, RoundingMode.HALF_UP).compareTo(otherValue) == 0;

    System.out.println("compareTo: " + test);
}
}
like image 165
Mike Avatar answered Sep 16 '25 03:09

Mike


public static final boolean isWithinTolerance(final BigDecimal bigDecimal1, final BigDecimal bigDecimal2, final BigDecimal tolerance)
{
    if (bigDecimal1 == null || bigDecimal2 == null || tolerance == null)
    {
        return false;
    }

    final BigDecimal diff = bigDecimal1.subtract(bigDecimal2).abs();

    return diff.compareTo(tolerance) < 0;
}
like image 39
kayz1 Avatar answered Sep 16 '25 02:09

kayz1