0

I used code snippet below using RoundingMode.HALF_UP:

        Double value = new Double( "18.74");

        Double result = (value*75)/100;
        System.out.println("Result: "+result);

        BigDecimal roundedValue = BigDecimal.valueOf(result).setScale(2, RoundingMode.HALF_UP);
        System.out.println("Rounded Value: "+roundedValue);

It gave me the result below:

Result: 14.054999999999998
Rounded Value: 14.05

But the expected value should be 14.06 How fix the issue?Are there any suggestions?

  • 1
    Is it? You round half up on scale 2 - so basically you are rounding 14.054 up to 14.05? – Worthless Aug 31 '18 at 07:26
  • 3
    Do your whole calculation with BigDecimal, don’t start with a double. That way you’ll riund 14.055 to 14.06 correctst – Erwin Bolwidt Aug 31 '18 at 07:51
  • Indeed, you can already see that the problem occurs before rounding - you're starting with 14.054999999999998 when presumably you expected to start with 14.055. The rounding is behaving exactly correctly with that input. – Jon Skeet Aug 31 '18 at 07:57
  • 1
    If you start with `new BigDecimal("18.74").multiply(BigDecimal.valueOf(75)) .divide(BigDecimal.valueOf(100))` you'll get the answer you expect. – Jon Skeet Aug 31 '18 at 07:57
  • Thanks @Erwin Bolwidt, it works when using BigDecimal. –  Aug 31 '18 at 10:34
  • Thanks @Jon Skeet , it works when using BigDecimal –  Aug 31 '18 at 10:34

0 Answers0