What is the purpose of the MathContext parameter in the methods of BigDecimal class?

296 Views Asked by At

The BigDecimal class has the following arithmetic and rounding methods:

BigDecimal add     (BigDecimal y)
BigDecimal subtract(BigDecimal y)
BigDecimal multiply(BigDecimal y)
BigDecimal divide  (BigDecimal y, [int scale,] RoundingMode rm)
BigDecimal setScale(int scale, RoundingMode rm)

The divide and setScale methods have the scale parameter, which defines the number of digits after the decimal point in the method result. We can use this parameter to round a number, for example, to 2 decimal places in order to display it to a user or store them in a database.

Java 5 introduced the following new methods to the BigDecimal class:

BigDecimal add     (BigDecimal y, MathContext mc)
BigDecimal subtract(BigDecimal y, MathContext mc)
BigDecimal multiply(BigDecimal y, MathContext mc)
BigDecimal divide  (BigDecimal y, MathContext mc)
BigDecimal round   (MathContext mc)

The MathContext mc parameter defines the precision of a method result, that is the total number of digits in it, i.e. both before and after the decimal point. But what is the purpose of the mc parameter? I don't think it is, for example, for rounding a number to 7 digits in order to display it to a user, because what's the point of rounding to 7 digits if the rounded numbers have a different number of digits after the decimal point? Maybe it is for defining the precision of intermediate results, e.g. resulting from the division 1/3 = 0.3333333333333333?

Unfortunately, the purpose of MathContext parameters isn't described in API documentation. I have no code to show, I am only learning Java and wonder about the meaning of this parameter.

0

There are 0 best solutions below