Java – How to round double / float value to 2 decimal points

Java – How to round double / float value to 2 decimal points

In Java, there are a few ways to round float or double to 2 decimal places

1. DecimalFormat

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class DecimalFormat
{
    
     private static DecimalFormat df = new DecimalFormat("0.00");

    public static void main(String[] args) {

        double input = 2105.1234;

        System.out.println("salary : " + input);

        // DecimalFormat, default is RoundingMode.HALF_EVEN
        System.out.println("salary : " + df.format(input));      //1205.64
        
        df.setRoundingMode(RoundingMode.DOWN);
        System.out.println("salary : " + df.format(input));      //1205.63

        df.setRoundingMode(RoundingMode.UP);
        System.out.println("salary : " + df.format(input));      //1205.64

    }
}

 

Output

salary : 2105.1234
salary : 2105.12
salary : 2105.12
salary : 2105.13

 

2. BigDecimal

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalExample {

    public static void main(String[] args) {

        double input = 3.1123435;
        System.out.println("double : " + input);

        BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP);
        double salary = bd.doubleValue();

        System.out.println("salary : " + salary);

    }

}

 

Output

double : 3.1123435
salary : 3.11

 

3. Math.round

public class MathExample {

    public static void main(String[] args) {

        double input = 1120.1235;

        System.out.println("salary : " + input);

        double salary = Math.round(input * 100.0) / 100.0;

        System.out.println("salary : " + salary);

    }

}

 

Output

salary : 1120.1235
salary : 1120.12