How do I check if a BigDecimal is in a Set or Map in a scale independent way?

后端 未结 3 835
醉酒成梦
醉酒成梦 2021-01-17 17:42

BigDecimal\'s equals() method compares scale too, so

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

It\'s c

3条回答
  •  不要未来只要你来
    2021-01-17 18:21

    Use the compareTo method of BigDecimal.

    BigDecimal("0.200").compareTo(new BigDecimal("0.2")) == 0; // Means they are equal.
    

    From the JavaDoc

    Compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) 0), where is one of the six comparison operators.

提交回复
热议问题