Search code examples
javaroundingbigdecimal

Rounding to the nearest hundered-thousandths


I'm facing an issue while trying to round up the decimal places in a number to the nearest hundered-thousandth digit.

Example :

BigDecimal num1 = BigDecimal.valueOf(0.38871551);
MathContext mc = new MathContext(5);
System.out.println(num1.round(mc));

The output is 0.38872 which is as expected. All good so far. Let's take another example :

BigDecimal num1 = BigDecimal.valueOf(1.1680418);
MathContext mc = new MathContext(5);
System.out.println(num1.round(mc));

The output is 1.1680. This is where the problem arrises. What I want is the output to be 1.16804 but the rounding seems to eat up the 4 instead of leaving it as it is.

I tried different rounding modes but this is what I get :

  • RoundMode.UP gives 1.1681
  • RoundingMode.HALF_UP or RoundingMode.HALF_DOWN give 1.1680 and so on..

How do I get the desired output :

  • 0.38871551 should round to 0.38872
  • 1.1680418 should round to 1.16804
  • 0.55052984 should round to 0.55053

I even tried rounding to the 6th decimal place instead of the 5th but I'm not able to find the right combination that gives me the desired output as shown above.


Solution

  • You can try it with setScale Function of BigDecimal

    num1 = num1.setScale(5, BigDecimal.ROUND_HALF_UP);