The java.math.MathContext class provides immutable objects that encapsulate context settings and define those numerical operator rules, such as those that the BigDecimal class implements.
The base-independent configurations are as follows:
- Precision: The number of digits to be used for an operation; this accuracy is rounded to results.
- RoundingMode: a RoundingMode object that determines the rounding algorithm to be used.
The number of significant digits is specified by the precision. The default mode in rounding off is HALF_UP mode which will be introduced in later part.
Suppose a random number say be it 123 is selected and the task now is to round off for 2 significant digits, you’re going to get 120. It might be more apparent if you think in terms of scientific notation. As in scientific notations, 123 would be 1.23e2. 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. If you use 123 as the number and ask for 2 significant digits, you’ve reduced your accuracy to reuse the example. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you’ll get 130.
Syntax: Class declaration
public final class MathContext extends Object implements Serializable
- MathContext(int setPrecision): This constructor constructs a new MathContext with the specified precision and the HALF_UP rounding mode.
- MathContext(int setPrecision, RoundingMode setRoundingMode): This constructor constructs a new MathContext with a specified precision and rounding mode.
- MathContext(String val): This constructor constructs a new MathContext from a string.
Now, dwelling onto the methods present in this class, later on, to be used in the implementation part in the program for the same. Method Description
equals(Object x) This method compares this MathContext with the specified Object for equality. getPrecision() This method returns the precision setting. getRoundingMode() This method returns the roundingMode setting. hashCode() This method returns the hash code for this MathContext. toString() This method returns the string representation of this MathContext.
246.8 2.5E+2 2.5E+2 2E+2 3E+2
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.