Comparing BigDecimals using equals

0


One important thing to know when you are comparing BigDecimals in Java is that the equals method returns true only if the objects being compared are equal in value and scale . So 3.14 not equals 3.140 if you are using the equals method .

Alternatives that can be used .

The compareTo method in BigDecimal is the obvious alternative to overcome the issue mentioned above . Another way would be to use the stripTrailingZeros methods on both objects before comparing them with equals .
However ,the stripTrailingZeros method does create a new object , and so might have
an performance overhead .


BigDecimal d1=new BigDecimal("3.14"); BigDecimal d2=new BigDecimal("3.140"); System.out.println(d1.equals(d2)); System.out.println(d1.compareTo(d2)==0); System.out.println(d1.stripTrailingZeros().equals(d2.stripTrailingZeros()));

Read more »

0 comments:

Post a Comment

© Zone817. Powered by Blogger.