0

I am curious to understand why do we see BigDecimal.Zero but not Double.Zero, so if we need to assign a double variable as Zero then we need to cast it to (double) 0.

Any specific reasons creators added a special zero variable for bigdecimal.

Raj Saraogi
  • 1,780
  • 1
  • 13
  • 21
  • *so if we need to assign a double variable as Zero then we need to cast it to (double) 0.* We don't. As @user16320675 has just said, we assign `0.0` – g00se Jun 24 '23 at 08:17
  • You can also use `0D` or `0d` instead of `0.0`. – Rob Spoor Jun 24 '23 at 11:26

1 Answers1

1

so if we need to assign a double variable as Zero then we need to cast it to (double) 0.

No. This compiles:

double d = 0;

so does this:

double d = 0.0;

The first one works because assignment contexts allow a widening primitive conversion (from int to double).

If you're talking about the Double wrapper, this also compiles:

Double d = 0.0;

There is a zero value for double that you can easily write - in fact, more easily than BigDecimal.ZERO - it's just written 0.0. And because assignment contexts allow a boxing conversion, you can assign 0.0 to the wrapper Double too.

BigDecimal.ZERO is not the rule - it's the exception. The compiler knows about all the primitive numeric types, and their "zeroes" are baked into the language - 0, 0L, 0.0, 0.0f etc.

The compiler doesn't know about BigDecimal. BigDecimal is just a part of the JDK, the standard library, not a part of the Java language.

The language specifications does not say that there is a conversion from double to BigDecimal in an assignment context, so you can't do

BigDecimal d = 0.0;

And that's why there is BigDecimal.ZERO.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • `double d = 0;` *compiles* as it undergoes a [widening conversion](http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25214) – g00se Jun 24 '23 at 08:34
  • @g00se I didn't think that was relevant to the question at first. But upon rereading it, I guess you're right - I should include that. – Sweeper Jun 24 '23 at 08:50
  • You can also have negative signed zero `double d = -0.0; System.out.println(d);` https://en.wikipedia.org/wiki/Signed_zero – axelclk Jun 25 '23 at 09:26
  • BigDecimal doesn't distinguish signed zeros: https://stackoverflow.com/questions/49774540/distinguish-zero-and-negative-zero-with-java-math-bigdecimal – axelclk Jun 25 '23 at 09:34