Set BigDecimal precision only if duplicate decimal places

I know that I can use a method BigDecimal.divide()

to set fixed precision:

BigDecimal a1 = new BigDecimal(1);
BigDecimal a2 = new BigDecimal(3);
BigDecimal division = a1.divide(a2,5,1); //equals 0.33333

      

But if the division result is exact:

BigDecimal a1 = new BigDecimal(1);
BigDecimal a2 = new BigDecimal(4);
BigDecimal division = a1.divide(a2,5,1); //equals 0.25000

      

How can I set the result of the division so that if the division ends up with an exact result, it will just give a result of 0.25 instead of 0.25000?

I also tried not to specify the precision by doing:

BigDecimal division = a1.divide(a2);

      

it will manage to give the result 0.25

when executed 1/4

, but when it does division like 1/3

or 2/3

, it results in runtime ArithmeticException

.

a1

and a2

are created from user input.

Is there a way to solve this?

+3


source to share


1 answer


You get ArithmeticException

, as described in BigDecimal.divide(BigDecimal)

- "if the exact coefficient has no finite decimal expansion", because correctly representing the result 1/3

will take up infinite memory. By using BigDecimal.divide(BigDecimal,int,RoundingMode)

, you explicitly set what precision you will tolerate, that is, any division can be approximated in memory.

For consistency, this version of division always sets the scale for what you specify, even if the value can be accurately represented with less precision. If this were not the case, you would have a hard time speculating about how accurate any future calculations using this result are.



To reduce the accuracy of use .stripTrailingZeros()

; this effectively reduces the scale to a minimum. Do this as close to the process as possible (i.e. just before printing) to maintain the above consistency.

You might also want .toPlainString()

if you try to display these values โ€‹โ€‹nicely, as it will .stripTrailingZeros()

itself display 100

as 1E+2

.

+6


source







All Articles