3 ms·
Yeah, my bad, I was thinking about rounding. I'm surprised that a.add(b) promotes to an extra decimal place. That's a touch ... odd.
by bsder 2y ago
Yeah, my bad, I was thinking about rounding.
I'm surprised that a.add(b) promotes to an extra decimal place.
That's a touch ... odd.
- wging 2y agoYou could also think of it as declining to _lose_ a decimal place; a.add(b) ought to be the same as b.add(a), so there's no reason to prefer a's precision to b. You need to take the higher precision of the two for an exact result; I assume that's the rationale. > The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown ... - https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html https://docs.oracle.com/javase/8/docs/api/java/math/BigDecim...
- wging 2y agohttps://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/math/BigDecimal.html https://docs.oracle.com/en/java/javase/21/docs/api/java.base... is probably a better link (though it's not that different)
- bsder 2y agoThanks for the link. Apparently, restricted behavior like I expected is reserved for if you use a MathContext. > Instead, for the BigDecimal operations taking a MathContext parameter, if the MathContext has a nonzero precision, the set of possible representable values for the result is determined by the precision of the MathContext argument. Very strange. I would have expected something that is going to be mostly used for currency to not do implicit things by default.