We know that to compare floating point values we should use epsilon and not just compare bits. We may run into similar issues when comparing BigDecimal
in Java:
1 2 3 |
BigDecimal a = BigDecimal.valueOf(0); BigDecimal b = BigDecimal.valueOf(Double.valueOf(0)); System.out.println(a.equals(b)); |
What is the output? Of course it is false
, otherwise I wouldn’t write this post. This is because BigDecimal
includes scale
:
1 |
Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method). |
So we should use this:
1 |
System.out.println(a.compareTo(b)); |
and then the result is as we expect.