BigDecimal .equals scale comparison
I ran into an issue this morning with the java BigDecimal equals implementation. When comparing the two BigDecimal objects
BigDecimal one = new BigDecimal(1);
BigDecimal two = new BigDecimal(1.0);
they do not equal using .equals().
one.equals(two) == false
There are benefits of doing the comparison this way since the number of decimal places are considered. However, in some cases code is just being converted from double/Double to BigDecimal. In those scenarios the way to consider the objects equal by value is to use the .compareTo() method.
boolean equal = one.compareTo(two) == 0;
Written by Matt Conroy
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Related Tags
#java
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#