How to truncate a BigDecimal without rounding
I faced an issue truncating when I was using one BigDecimal to set another. The source could have any value with different decimal values.
BigDecimal source = BigDecimal.valueOf(11.23); // could 11 11.2 11.234 11.20 etc
In order to truncate and scale this correctly for two decimals, I had to use the string value of the source instead of the BigDecimal or double value.
new BigDecimal(source.toPlainString()).setScale(2, RoundingMode.FLOOR))
I used this for currency and this always results in values with 2 decimal places.
- 11 -> 11.00
- 11.2 -> 11.20
- 11.234 -> 11.23
- 11.238 -> 11.23
- 11.20 -> 11.20
Use the setScale override that includes RoundingMode:
value.setScale(2, RoundingMode.DOWN);
Use either RoundingMode.DOWN or RoundingMode.FLOOR.
BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);