BigDecimal.equals()may produce unintended results JAVA-W1083
The Java analyzer has found a usage of
BigDecimal.equals() in the code. This method may produce unintended results; it will also compare the scales of the two values, which can lead to it returning false even if the two values are equivalent.
The scale of a
BigDecimal value can be thought of as the number of digits to the right of the decimal point in the value.
BigDecimal bd = BigDecimal.valueOf(3200); // 32 * 10^-(-2) in terms of the input values. BigDecimal bd2 = BigDecimal.valueOf(32, -2);
bd has a scale of
bd2 has a scale of
Now, if we compare the two values with the
equals() method, we would find that it returns
false, because the scales aren't the same.
assertTrue(bd.equals(bd2)); // throws.
compareTo() method instead. This method correctly compares the actual values of the two numbers, and will return
0 if the two numbers are numerically identical.
assertEquals(0, bd.compareTo(bd2)); // Works.