we might see two way of setting round in BigDecimail:
// 1. BigDecimal r1 = new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP)); // 2. BigDecimal r2 = new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
r1 is 35.35
r2 is 35.3456
There is big difference.
But when you look at the JavaDocs, you’ll find that the MathContext constructor is accepting not a scale argument but aprecision one:
MathContext(int setPrecision, RoundingMode setRoundingMode)
One important point that is alluded to but not directly addressed is the difference between“precision” and “scale” and how they are used in the two statements. “precision” is the total number of digits in a number (number of significant digits. The precision of 0.000042M is 2. ). “scale” is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.