Search code examples
javabigdecimal

Using setScale in BigDecimal


Can anyone helpme out with BigDecimal, I'm a newbie in it I want to round of 24.33 to 25.00 I just need to perform ceiling operation so I did something like this

BigDecimal amount = new BigDecimal("24.33");
System.out.println(amount.setScale(2, RoundingMode.CEILING));

I was expecting to get 25.00 but I'm still getting 24.33 any idea's where am i going wrong?


Solution

  • The scale applies to the part after the decimal point. What you want is:

    BigDecimal amount = new BigDecimal("24.33");
    System.out.println(amount.setScale(0, RoundingMode.CEILING));
    

    Also remember BigDecimals are Immutable, and so all operations return a new BigDecimal representing the result of the operation. Can catch you out if you're not used to it.