Search code examples
javabigdecimal

How to set specific precision to BigDecimal in Java?


I have BigDecimal value.

BigDecimal price = new BigDecimal("100500100500.9999999").setScale(2, BigDecimal.ROUND_HALF_EVEN);

It prints 100500100501.00, although I need 100500100500.99. Is it possible to make some restriction to precision evaluating?


Solution

  • You can use the rounding mode constant ROUND_DOWN in setScale. However, the overloaded setScale method that takes a RoudingMode is preferred.

    BigDecimal price = new BigDecimal("100500100500.9999999")
        .setScale(2, RoundingMode.DOWN);
    

    Output:

    100500100500.99