Java – how do I check if BigDecimal is in a scale independent manner in a set or map?

BigDecimal's equals () method is also relatively large, so

new BigDecimal("0.2").equals(new BigDecimal("0.20")) // false

This is contested why it behaves

Now, suppose I have a set < BigDecimal >, how can I check whether 0.2 in the set is independent?

Set<BigDecimal> set = new HashSet<>();
set.add(new BigDecimal("0.20"));
...
if (set.contains(new BigDecimal("0.2")) { // Returns false,but should return true
    ...
}

Solution

If you switch the HashSet to a TreeSet, the contains () will run as required

It is different from most collections because it will determine the equation based on the compareto() method instead of equals() and hashcode():

And since BigDecimal Compareto() compares without considering scale, which is exactly what you want

Alternatively, you can ensure that all elements in the collection are the same, minimize, and always use striptrailingzeros (both add() and on()):

set.add(new BigDecimal("0.20").stripTrailingZeros());
...
if (set.contains(new BigDecimal("0.2").stripTrailingZeros()) {
  ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>