Comparing BigDecimals

suggest change

The method compareTo should be used to compare BigDecimals:

BigDecimal a = new BigDecimal(5);
a.compareTo(new BigDecimal(0));    // a is greater, returns 1
a.compareTo(new BigDecimal(5));    // a is equal, returns 0
a.compareTo(new BigDecimal(10));   // a is less, returns -1

Commonly you should not use the equals method since it considers two BigDecimals equal only if they are equal in value and also scale:

BigDecimal a = new BigDecimal("5.00");
a.equals(new BigDecimal("5.00"));  // value and scale are equal, returns true
a.equals(new BigDecimal("5"));     // value is equal but scale is not, returns false
a.compareTo(new BigDecimal("5"));  // compareTo ignores scale, returns 0

new BigDecimal(5.00) does not show this. 5.00 is a double, and that value is exactly 5, so the double constructor produces the same scale-0 number as new BigDecimal(5). Use a string when the scale matters.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents