Home > database >  Comparison between DoubleRounder and BigDecimal RoundingMode
Comparison between DoubleRounder and BigDecimal RoundingMode

Time:12-10

I want to know if there is any advantage of using BigDecimal RoundingMode method over DoubleRounder.round().

Also I observe the differences in the result when I try to use the same precision in two methods. For Example :

Using DoubleRounder.round()

System.out.println("" DoubleRounder.round(0.0897435897435897, 5));  //gives 0.08974

Using BigDecimal RoundingMode

BigDecimal b= new BigDecimal(0.0897435897435897);

System.out.println("" b.round(new MathContext(5,RoundingMode.CEILING)); //gives 0.089744

I see that there are 6 digits in decimal places while using BigDecimal instead of 5. Can anyone explain me why this is happening. And in case I want to have exact 5 digit after decimal using BigDecimal, how do I need to modify this part of code?

CodePudding user response:

MathContext accept precision, it means starts from the leftmost nonzero digit.

you can use bigDecimal.setScale(5, RoundingMode.CEILING). scale is the number of digits to the right of the decimal point.

e.g. System.out.println(b.setScale(5, RoundingMode.CEILING)); // gives you 0.08975

CodePudding user response:

It will give you 5 digit

System.out.println("" b.round(new MathContext(4,RoundingMode.CEILING))); //gives 0.08975
  • Related