Search code examples
javaprecisionbigdecimal

Properly scaling BigDecimal


I have a situation where I want to scale values but in certain situations I'm getting an exception that indicates that rounding is required.

Lets say I have the numbers -9.999999 and 9.999999

Lets also say that I only care about precision up to 4 points after the decimal place. How can I scale both of these numbers properly without checking if the value is positive or negative?

If for example, I use RoundingMode.FLOOR, I get:

9.999999 scales to 99999
-9.999999 scales to -100000

What I would like is 9.9999 and -9.9999, respectively.

Do I really need to check for the sign here? I feel like I'm missing something.


Solution

  • RoundingMode.DOWN always rounds toward zero, so that should be what you're looking for. That is, it will never increment your final digit when it rounds. It's equivalent to truncating your value at the specified scale.