Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum precision below unlimited?

Tags:

java

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

like image 551
4thfloorstudios Avatar asked Aug 07 '13 15:08

4thfloorstudios


1 Answers

First Question: There is no such thing as BigDecimal.UNLIMITED. That doesn't make any sense. What is one less than infinity? Because the docs don't explicitly mention the default MathContext of a BigDecimal, I have to assume that it is 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.

like image 143
supersam654 Avatar answered Sep 27 '22 23:09

supersam654