61

I want to set scale of two BigDecimal numbers a and b . as in this example :

BigDecimal a = new BigDecimal("2.6E-1095");
        BigDecimal b = new BigDecimal("2.7E-1105");
        int i = 112, j=1;

        BigDecimal aa = a.setScale(i+j);
        BigDecimal bb = b.setScale(i+j);

and when i run i have this exception:

java.lang.ArithmeticException: Rounding necessary
    at java.math.BigDecimal.divideAndRound(BigDecimal.java:1439)
    at java.math.BigDecimal.setScale(BigDecimal.java:2394)
    at java.math.BigDecimal.setScale(BigDecimal.java:2437)

Why rounding is necessary ? if i don't want to make around, what is solution please ?

Thanks

Mehdi
  • 2,160
  • 6
  • 36
  • 53
  • 1
    Indeed it is a surprise. Without looking at docs I expected setting the scale to truncate at the scale... – Brian Knoblauch Apr 26 '16 at 19:24
  • I expectedthe same thing. This exception even comes when specifying the RoundingMode.ROUNDING_UNNECESSARY. I didn't see a truncate option, but wish there was. – wheeleruniverse Jul 11 '18 at 21:05

3 Answers3

45

You have two BigDecimal numbers both of which require over a 1000 decimal places. Trying to set the scale to only have 113 decimal places means you will lose precision and therefore you need to round.

You can use the setScale methods that take a RoundingMode to prevent the exception but not the rounding.

Jus12
  • 17,824
  • 28
  • 99
  • 157
brain
  • 5,496
  • 1
  • 26
  • 29
31

Try to use rounding mode of setScale method.

Some thing like:

BigDecimal aa = a.setScale(i+j, RoundingMode.HALF_DOWN);
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
Akostha
  • 679
  • 7
  • 8
9

Rounding is necessary.

In javadoc for BigDecimal, it says BigDecimal is represented as (unscaledValue × 10-scale), where unscaledValue is an arbitatrily long integer and scale is a 32-bit integer.

2.6*10-1095 requires a scale of at least 1096 to represent accurately. It can not be represented accurately with (any integer)*10-113. Therefore, you need to providing a roundingMode.

Haozhun
  • 6,331
  • 3
  • 29
  • 50