Round off Double value to 2 decimal places in Java

In this article, you will see how to round off double value upto 2 decimal.

Following code allows you to round a double value upto 2 decimal places using DecimalFormat class.

package com.kruders.java;
 
import java.text.DecimalFormat;  
 
public class RoundOffDouble {
    public static void main(String[] args) {  
        roundOffDouble(1.56555);  
        roundOffDouble(233);  
        roundOffDouble(32323.0);  
        roundOffDouble(233.523232);  
    }  
 
    private static void roundOffDouble(double d) { 
        DecimalFormat fmt = new DecimalFormat("0.00");
        String string = fmt.format(d);   
     
    System.out.println("The double: " + d + " formatted to 2 decimal places is: " +  string);
    }  
}

Output is :

The double: 1.56555 formatted to 2 decimal places is: 1.57
The double: 233.0 formatted to 2 decimal places is: 233.00
The double: 32323.0 formatted to 2 decimal places is: 32323.00
The double: 233.523232 formatted to 2 decimal places is: 233.52

You can select any number of decimal places. For example DecimalFormat(“0.000”); rounds to 3 decimal places.

One Response to Round off Double value to 2 decimal places in Java