- Published on
Java's BigDecimal Equals Does Not Behave As Expected
- Authors
- Name
- Yair Mark
- @yairmark
As mentioned in my previous post I ran into a weird bug that only surfaced when I used real data instead of test data in one of my tests. The reason for this is that in my test data I used BigDecimal.ZERO
which Java sees as different to BigDecimal.valueOf(0.0)
.
BigDecimal.ZERO == BigDecimal.valueOf(0.0)
This code will evaluate to false as Kotlin converts this to the following Java code BigDecimal.ZERO.equals(BigDecimal.valueOf(0.0));
which Java sees as different as per this post.
A workaround for this is to use BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0.0)) == 0
in your Java and Kotlin code. Or in Kotlin use only the >
and <
operators as Kotlin will compile these to compareTos when it compiles to Java. The following all return true:
BigDecimal.valueOf(1) > BigDecimal.ZERO
BigDecimal.valueOf(0.001) > BigDecimal.ZERO
BigDecimal.valueOf(-1) < BigDecimal.ZERO
BigDecimal.ZERO.compareTo(BigDecimal.valueOf(0.0)) == 0