Why BigDecimal(“5.50”) not equals to BigDecimal(“5.5”) and how to work around this issue?

前端 未结 3 1476
不知归路
不知归路 2020-12-03 02:18

Actually, I\'ve found possible solution

//returns true
new BigDecimal(\"5.50\").doubleValue() == new BigDecimal(\"5.5\").doubleValue()

Of

3条回答
  •  情歌与酒
    2020-12-03 02:45

    From the javadoc of BigDecimal

    equals

    public boolean equals(Object x)

    Compares this BigDecimal with the specified Object for equality. 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).

    Simply use compareTo() == 0

提交回复
热议问题