Search code examples
javaroundingbigdecimal

BigDecimal Rounding modes


We are replacing some sybase code to Java and having issue with Rounding BigDecimal to match what sybase returns

11.4443999999999999062083588796667754650115966796875 - Should return 11.44

and

35.9549999999999982946974341757595539093017578125 - should return 35.96

I have tried all different rounding options with scale set to 2, but none works for both. What is the best option?


Solution

  • You'll have to take a two-step approach. First round to scale 3, then to scale 2, using RoundingMode.HALF_UP:

    BigDecimal value1 = new BigDecimal("11.4443999999999999062083588796667754650115966796875");      
    BigDecimal value2 = new BigDecimal("35.9549999999999982946974341757595539093017578125"); 
    
    BigDecimal rounded1 = value1.setScale(3, RoundingMode.HALF_UP); // 11.444
    rounded1 = rounded1.setScale(2, RoundingMode.HALF_UP);          // 11.44
    
    BigDecimal rounded2 = value2.setScale(3, RoundingMode.HALF_UP); // 35.955
    rounded2 = rounded2.setScale(2, RoundingMode.HALF_UP);          // 35.96