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

后端 未结 3 809
醉酒成梦
醉酒成梦 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:07

    HashSet#contains method can't serve your requirement, it implicitly call equals method. You should iterate over Set and use compareTo method. If value is found than set a flag.

        Set set = new HashSet<>();
        set.add(new BigDecimal("0.20"));
        boolean found=false;
        for (BigDecimal bigDecimal : set) {
            if(bigDecimal.compareTo(new BigDecimal("0.2"))==0){
                System.out.println("Value is contain");
                found=true;
                break;
            }
        }
        if(found)// Use this flag for codition.
    

提交回复
热议问题