为什么我的 BigDecimal 0.0000 不等于 BigDecimal.ZERO?

Why is my BigDecimal 0.0000 not equal to BigDecimal.ZERO?

我在 Android Java 中得到以下表达式:

myVar + " == 0 ? " + BigDecimal.ZERO.equals(myVar)

输出如下:

0.0000 == 0 ? false

其中 myVar 声明为:

public BigDecimal myVar;

并成功分配 Gson,来自提供的 JSON 数据(我对此进行了检查以验证 JSON 是否良好)。 为什么 0.0000 作为 BigDecimal 不等于 BigDecimal.ZERO

来自the documentation

Returns true if x is a BigDecimal instance and if this instance is equal to this big decimal. Two big decimals are equal if their unscaled value and their scale is equal. For example, 1.0 (10*10-1) is not equal to 1.00 (100*10-2). Similarly, zero instances are not equal if their scale differs.

他们为什么这样决定?可能是因为它更容易实现。这是一个好的决定吗?我不这么认为,但事实就是如此。如果您不喜欢,请使用其他库。

an answer to another similar question中给出的一种解决方案是使用compareTo。因此,您可以将代码更改为

myVar + " == 0 ? " + (BigDecimal.ZERO.compareTo(myVar) == 0)