I am using BigDecimal to make some calculations. Recently I ran into:
java.lang.ArithmeticException:
Non-terminating decimal expansion; no exact representable decimal result.
The answer to that problem was posted here: ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"
This means, there is some division with unlimited decimals, so BigDecimal tells me it cannot calculate the result exactly. To avoid this I have to call BigDecimal.setScale(SOMETHING, ROUNDING_MODE);
EDIT:
The problem now is to set the SOMETHING to the maximum possible value. I could use a MathContext with precision below UNLIMITED (MathContext(precision)
) but the same problem occurrs there. There would need to be a value below
MathContext.UNLIMITED
...
Does anyone know how to accomplish that?
Moved my second question to: Why is there no BigDecimal.setPrecision() method?
Thank you!
Oliver
First Question: There is no such thing as Because the docs don't explicitly mention the default MathContext of a BigDecimal, I have to assume that it is BigDecimal.UNLIMITED
. That doesn't make any sense. What is one less than infinity?MathContext.UNLIMITED
. Seeing as you have a repeating decimal, a BigDecimal
can't hold it, even with unlimited precision. Instead, you need to arbitrarily pick a value (say 100 or 1000 - I have no idea what you are using these numbers for). If you only care about the first, say, 15 decimal places, you should never have a rounding error if you track the first, say, 100.
Second Question: Ask a separate question for it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With