Open In App

Java MathContext toString() Method

Last Updated : 16 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The MathContext.toString() method in Java is a part of java.math package. This method is used to define the precision and rounding behaviour for BigDecimal operations. This method returns the string representation of a MathContext object's context settings. The string returned represents the settings of the MathContext object as two space-separated words. These two space-separated strings are as follows :

  1. Precision: The number of digits used for mathematical operations.
  2. Rounding Mode: This specifies how values are rounded when precision loss occurs.

These are returned in the following format:

precision=<value> roundingMode=<mode>

For example, if a MathContext is created with a precision of 10 and a rounding mode of RoundingMode.HALF_EVEN, the toString() method will return,

precision=10 roundingMode=HALF_EVEN

Syntax of MathContext toString() Method

public String toString()

  • Parameter: The method accept no parameters. 
  • Return Values: This method returns a string representing the context settings of the object of the MathContext class in the format mentioned above.

Examples of Java MathContext toString() Method

Example 1: In this example, we are going to create a MathContext object with a precision and rounding mode and then print its settings using the toString() method.

Java
// Java program to display MathContext 
// settings with custom precision and rounding mode
import java.math.MathContext;
import java.math.RoundingMode;

public class Geeks {
    
    public static void main(String[] args) {
        
        MathContext mc = new MathContext(2, RoundingMode.HALF_DOWN);  
        System.out.println(mc.toString());  
    }
}

Output
precision=2 roundingMode=HALF_DOWN


Example 2: In this example, we are going to create a MathContext object using only the precision. Java will use the default rounding mode HALF_UP.

Java
// Java program to demonstrate 
// MathContext with default rounding mode
import java.math.MathContext;

public class Geeks {
    
    public static void main(String[] args) {
        
        // only precision is set
        MathContext mc = new MathContext(15);  
        System.out.println(mc.toString());     
    }
}

Output
precision=15 roundingMode=HALF_UP

Explanation: Here, only precision of 15 is used and the rounding mode defaults to HALF_UP.


When to Use MathContext toString() Method

The toString() method is useful when:

  • We want to log or print the current precision and rounding configuration.
  • We are debugging complex arithmetic logic in financial or any other applications.
  • We need to confirm that a MathContext object is set up correctly.

Reference : https://docs.oracle.com/javase/7/docs/api/java/math/MathContext.html#toString()


Practice Tags :

Similar Reads