javaroundingbigdecimalarithmeticexception

How to truncate a BigDecimal without rounding


After a series of calculations in my code, I have a BigDecimal with value 0.01954

I then need to multiply this BigDecimal by 100 and I wish the calculated value to be 1.95

I do not wish to perform any rounding up or down, I just want any values beyond two decimal places to be truncated

I tried setting scale to 2, but then I got an ArithmeticException saying rounding is necessary. How can I set scale without specifying rounding?


Solution

  • Use either RoundingMode.DOWN or RoundingMode.FLOOR.

    BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);