How can we set the resolution of a BigDecimal so it can only ever take values that land in specified increments?

Viewed 144

Is it possible to set the resolution of the BigDecimal e.g. to 10–9, so values must be multiples of this value and nothing less.

Or does this have to be done when performing arithmetic operations via rounding?

1 Answers

This is what I was looking for

    BigDecimal val1 = new BigDecimal("1.00876876989",MathContext.DECIMAL128);

    // setting the scale to 10 sets the limits resolution, but the precision provided by the MathContext must be big enough to support this minimum resolution.
    // The rounding type doesn't matter but must be provided.

    val1 = val1.setScale(10, BigDecimal.ROUND_DOWN);
Related