Tag Archives: comparison

Java BigDecimal comparison

Why BigDecimal?, wasn’t it enough with all the previous numeric types to represent all the possible values?

No. When it comes to manage currency values, BigDecimal is the only class accurate enough to deal with them.

Anyway, this post is about its comparison, which may be very tricky. We’re used to the .equals method, so we may be tempted to use it to compare BigDecimal objects. Well, don’t. It does not work.

So what do we do to compare BigDecimal values a and b?, we must use the .compareTo() and .signum() methods.

 a.compareTo(b);  // returns (-1 if a < b), (0 if a == b), (1 if a > b)
 a.signum(); // returns (-1 if a < 0), (0 if a == 0), (1 if a > 0)

There you go 😉