Posts

Showing posts from October, 2009

Java: BigDecimal's Big Problems

In Java, the BigDecimal class has a failed abstraction around equality comparisons that will inevitably lead to bugs. There are 2 problems: 1. the method compareTo is inconsistent with the method equals Equality (equals) of two BigDecimals takes scales (number of decimal places) into account, whereas comparison (compareTo) doesn't. So, new BigDecimal("1.00").equals(new BigDecimal("1.0")) returns false, and new BigDecimal("1.00").compareTo(new BigDecimal("1.0")) returns 0 (zero), indicating that they're equal. I've seen some threads stating that equals is consistent with the way that an engineering (or scientific) quantity should work, where scale is very important. Since operations with numbers with different scales yield different results, it seems reasonable that equals returns false for these numbers. So, from this standpoint, the equals implementation is right, and compareTo should be consistent and retu