Search code examples
javabigdecimal

Rounding a BigDecimal in Java doesn't return the expected number


I have a property called m_FOBST which contains the following number: 1.5776. Here I'm trying to round it:

   this.m_FOBST.setScale(2, BigDecimal.ROUND_HALF_EVEN)

However, I get the number 1.60 when I should be getting 1.58.

Can anyone explain why?


Solution

  • BigDecimal is immutable - make sure you are using the value returned by the setScale() method.

    BigDecimal bd = new BigDecimal("1.5776");
    
    bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    

    In this case, bd is 1.58