BigDecimal multiply by zero
Solution 1:
You can't use the equals()
method to compare BigDecimals
, like this assertion does. That is because this equals function will compare the scale. If the scale is different, equals()
will return false, even if they are the same number mathematically.
You can however use compareTo()
to do what you want:
As @assylias points out, you should also use the new BigDecimal("22.3")
constructor to avoid double precision issues.
BigDecimal expected = BigDecimal.ZERO;
BigDecimal actual = new BigDecimal("22.3").multiply(BigDecimal.ZERO);
assertEquals(0, expected.compareTo(actual));
There is also a method called signum()
, that returns -1, 0 or 1 for negative, zero, and positive. So you can also test for zero with
assertEquals(0, actual.signum());
Solution 2:
There are 2 issues with your code:
- you should compare BigDecimal with compareTo instead of equals, as advised by the other answers
- but you should also use the string constructor:
new BigDecimal("22.3")
instead of the double constructornew BigDecimal(22.3)
to avoid double precision issues
In other words, the following code (which correctly uses compareTo) still returns false:
BigDecimal bd = new BigDecimal(0.1).multiply(new BigDecimal(10));
System.out.println(bd.compareTo(BigDecimal.ONE) == 0);
because 0.1d * 10d != 1