How does BigDecimal compare, but approximately?… here is a solution to the problem.
How does BigDecimal compare, but approximately?
I have this code :
BigDecimal d = ...;
if (d.compareTo(Expression.PI) == 0) {
do something
}
where Expression.PI is pi rounded to the 100th decimal place.
But I don’t need to compare if d equals pi to up to 100 decimal places, but just say up to 20 decimal places. In other words, how can you tell 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 neither of these seems to work. What am I doing wrong here?
Solution
As lucasvw mentioned in the comment, I think you’ve done it correctly and there must be something wrong with your “d” value. This is a test class that shows the correct results.
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);
}
}