I have an operation like below. As we see the numerator is -ve and denominator is +ve, so the division operation should have resulted in -ve. However, when I run the below code I get 0.0. I understand that 0 does not have any sign, and since I'm rounding up the value to 2 positions after decimal, I end up getting 0.0. If I increase the scale more than 2, then I get -ve. But my requirement is to scale to 2 positions, but yet preserve the sign. As a work around, I can determine the sign explicitly looking at the signs of numerator and denominator, but wondering if there is any other way with in BigDecimal api.
Why BigDecimal is behaving differently from Double
BigDecimal has no way to represent the concept of -0.0. It also can't represent values like Double.POSITIVE_INFINITY or Double.NaN - these throw exceptions when you try to construct them. But a double -0.0 just gets converted into a BigDecimal 0, because for most purposes, that's the same thing. What sort of application are you writing where someone thinks it's important to distinguish between 0.0 and -0.0? If that's really necessary, you'll need to either (a) not use BigDecimal, or (b) maintain the sign of the result separately from the BigDecimal value.
And by the way what is the difference between 0.0 and -0.0?
And how many folks are going to be confused with seeing -0.0?
The reason floating point types make the distinction is so that when a calculation brings us closer to zero than their precision can represent, we at least know a) that it's not quite zero, and b) which side of zero it's on.
Java supports three kinds of arithmetic: integer (int, etc), floating‑point (double, etc) and decimal in BigDecimal. Floating‑point arithmetic has certain features (eg -0.0, ±∞) which the other two types do not support. Don’t try to mix floating‑point arithmetic and decimal arithmetic.