@jatan
Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
There's nothing special about BigDecimal.round()
vs. any other BigDecimal
method. In all cases, the MathContext
specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext
. There's a precision, and there's also a RoundingMode
.
The precision again specifies the number of significant digits. So if you specify 123
as a number, and ask for 2 significant digits, you're going to get 120
. It might be clearer if you think in terms of scientific notation.
123
would be 1.23e2
in scientific notation. If you only keep 2 significant digits, then you get 1.2e2
, or 120
. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
The RoundingMode
part specifies how we should handle the loss of precision. To reuse the example, if you use 123
as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode
of HALF_UP
(the default mode), 123
will become 120
. With a RoundingMode
of CEILING
, you'll get 130
.
For example:
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
Outputs:
123.4
1.2E+2
1.3E+2
2E+2
You can see that both the precision and the rounding mode affect the output.