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

时间:2015-07-28 22:36:21

标签: java android bigdecimal

I've got the following expression in Android Java:

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

which outputs the following:

0.0000 == 0 ? false

Where myVar is declared as:

public BigDecimal myVar;

And assigned successfully with Gson, from served JSON data (I inspected this to verify the JSON was good). Why does 0.0000 as a BigDecimal not equal BigDecimal.ZERO?

2 个答案:

答案 0 :(得分:5)

From 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.

Why did they decide this? Probably because its easier to implement. Is it a good decision? I don't think so, but it is what it is. Use another library if you don't like it.

答案 1 :(得分:1)

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

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