Monday, February 23, 2009

BigDecimal gotchas

The BigDecimal class is full of gotchas. Today's gotcha is:

new BigDecimal("1").equals(new BigDecimal("1.00")) == false

To avoid this problem, use compareTo instead of equals.


Another nice gotcha is:
new BigDecimal(1.23) == 1.229999999999999982236431605997495353221893310546875
The correct way:
new BigDecimal("1.23")