Using ==
to compare doubles seems like a bad idea in general.
You could call setScale to the same thing on the numbers you're comparing:
new BigDecimal ("5.50").setScale(2).equals(new BigDecimal("5.5").setScale (2))
where you would be setting the scale to the larger of the two:
BigDecimal a1 = new BigDecimal("5.051");
BigDecimal b1 = new BigDecimal("5.05");
// wow, this is awkward in Java
int maxScale = Collections.max(new ArrayList() {{ a1.scale(), b1.scale()}});
System.out.println(
a1.setScale(maxScale).equals(b1.setScale(maxScale))
? "are equal"
: "are different" );
Using compareTo() == 0
is the best answer, though. The increasing of the scale of one of the numbers in my approach above is likely the "unnecessary inflation" that the compareMagnitude method documentation is mentioning when it says:
/**
* Version of compareTo that ignores sign.
*/
private int compareMagnitude(BigDecimal val) {
// Match scales, avoid unnecessary inflation
long ys = val.intCompact;
long xs = this.intCompact;
and of course compareTo
is a lot easier to use since it's already implemented for you.