Search code examples
javaroundingscalebigdecimal

Is this the correct behavior for rounding with BigDecimals?


I am trying to round BigDecimals like this: 5.46597 -> 5.46, I thought the code below does this for me, but not.

I tried it with BigDecimal.round and BigDecimal.setScale.

BigDecimal bD = new BigDecimal(5.46597); // whole number: 5.4659700000000004393996277940459549427032470703125 
bD.setScale(2, RoundingMode.HALF_DOWN); // 5.47
bD.round(new MathContext(3, RoundingMode.HALF_DOWN)); // 5.47

Isn't this should be 5.46, or what do I misunderstood?


Solution

  • HALF_DOWN only rounds down when the actual value is exactly half-way between the two possible rounded values. I.e. 5.46500 -> 5.46. On the other hand 5.4650000001 -> 5.47 because that's nearer to 5.47 than 5.46.

    Perhaps what you're looking for is RoundingMode.DOWN, which always rounds down.