3

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?

Ky -
  • 30,724
  • 51
  • 192
  • 308
  • But please post the code that initializes/sets the value for `myVar`. – Mick Mnemonic Jul 28 '15 at 22:39
  • `myVar` is assigned from our custom JSON deserializer. "All relevant code" will end up being thousands of lines that you wouldn't want to read even if I was allowed to disclose it. Long story short: it is successfully converted from a JSON `0.0000` to an Android Java `BigDecimal` `0.0000`. – Ky - Jul 28 '15 at 22:49
  • 1
    Duplicate of http://stackoverflow.com/questions/3866514/why-bigdecimal5-50-not-equals-to-bigdecimal5-5-and-how-to-work-around-th – Alexis C. Jul 29 '15 at 23:26

2 Answers2

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.

Ky -
  • 30,724
  • 51
  • 192
  • 308
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • 2
    This makes me want to extend `BigDecimal` and add methods like `equalsIgnoreScale` – Ky - Jul 28 '15 at 22:44
3

One solution given in an answer to another similar question is to use compareTo. So, you could change your code to

myVar + " == 0 ? " + (BigDecimal.ZERO.compareTo(myVar) == 0)
Ky -
  • 30,724
  • 51
  • 192
  • 308
Baptiste Pernet
  • 3,318
  • 22
  • 47