How to implement rounding to two decimal places in Java division operation?

In Java, you can use the DecimalFormat class to achieve the function of dividing and rounding to two decimal places. Here is an example code:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double dividend = 10;
        double divisor = 3;
        
        double result = dividend / divisor;
        
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String formattedResult = decimalFormat.format(result);
        
        System.out.println(formattedResult);
    }
}

When running the above code, the output will be 3.33, showing the result of division with two decimal places. In the code above, the pattern string “#.00” in DecimalFormat is used to specify the two decimal places. Adjust the pattern string as needed to achieve different decimal place preservation.

bannerAds