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?
To get rid of some decimal places without and rounding, use TRUNC(), which is short of truncate. It takes two arguments: the value and the number of decimal places. Whatever is to the right of the specified decimal location is simply discarded. For example, =TRUNC(12.119999, 2) evaluates to 12.11.
5555555 as the truncating value is > 0.5 so it will round to x. 56 if you use BigDecimal newValue = myBigDecimal. setScale(2, RoundingMode.
You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.
Use either RoundingMode.DOWN or RoundingMode.FLOOR.
BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);
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