Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part.
From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online.
Please let me know if you have any idea on this.
@jatan
There's nothing special about
BigDecimal.round()vs. any otherBigDecimalmethod. In all cases, theMathContextspecifies the number of significant digits and the rounding technique. Basically, there are two parts of everyMathContext. There's a precision, and there's also aRoundingMode.The precision again specifies the number of significant digits. So if you specify
123as a number, and ask for 2 significant digits, you're going to get120. It might be clearer if you think in terms of scientific notation.123would be1.23e2in scientific notation. If you only keep 2 significant digits, then you get1.2e2, or120. By reducing the number of significant digits, we reduce the precision with which we can specify a number.The
RoundingModepart specifies how we should handle the loss of precision. To reuse the example, if you use123as the number, and ask for 2 significant digits, you've reduced your precision. With aRoundingModeofHALF_UP(the default mode),123will become120. With aRoundingModeofCEILING, you'll get130.For example:
Outputs:
You can see that both the precision and the rounding mode affect the output.