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?
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);
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With