Search code examples
javabigdecimal

BigDecimal rounding mode issue


I need to get these results using BigDecimal roundingmode.xxx and setScale(2) :

(5.789).setScale(2, RoundingMode.xxx) = 5.79

(2.894).setScale(2, RoundingMode.xxx) = 2.89

(2.895).setScale(2, RoundingMode.xxx) = 2.89

Where RoundingMode.xxx has to be same for the three given values.

Ive tried all combinations but with no success and Microsoft Excel set the three results with success.


Solution

  • The problem is when I was multiplying two BigDecimal numbers I got a big result. After that I used setScale(2, HalfDown) but did not get the desired result.

    The wrong result

    "2.89500004313886165618896484375".setScale(2, BigDecimal.ROUND_HALF_DOWN);
    

    I need 2.89 and the wrong result was 2.90

    Using .round(new MathContext(2)) I got it :

     "2.89500004313886165618896484375".round(new MathContext(2));
    

    The right result is 2.89