Showing posts with label decimal-places. Show all posts
Showing posts with label decimal-places. Show all posts

Tuesday, July 19, 2022

Java round double to decimal places with up and down rounding

This is a quick tutorial on how we can round the double or float value to x decimal places

Here we are using DecimalFormat class to do so. Let's look at the example. Here we are creating DecimalFormatter.java class

Round to x decimal places:

import java.text.DecimalFormat;

public class DecimalFormatter {

    public static void main(String[] args) {
        // normal format
        System.out.println("Normal format: " + format(2.0451, "0.00"));
        System.out.println("Normal format add extra zero: " + format(2.045, "0.00000"));
    }
    
    private static String format(double value, String precision) {
        DecimalFormat df = new DecimalFormat(precision);
        return df.format(value);
    }
}    

In the above example, we are using a default rounding mode i.e DecimalFormat by default uses half even rounding mode to format. i.e if the decimal value is greater or equal to 5 then it will round up for that precision else use the same value for that precision. Here, 2.0451 will be formatted to 2.05 as we are using the two decimal place 0.00

Also, in the second example, we have a double value of 2.045 but we are trying to round 0.00000 five decimal places so it will add the extra 2 zeros to the double value.

Output:

Normal format: 2.05
Normal format add extra zero: 2.04500

Round Up to x decimal places:

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

public class DecimalFormatter {

    public static void main(String[] args) {
        // round up format
        System.out.println("Round up format: " + formatRoundUp(1.03510001, "0.0000"));
    }
    
     private static String formatRoundUp(double value, String precision) {
        DecimalFormat df = new DecimalFormat(precision);
        df.setRoundingMode(RoundingMode.UP);
        return df.format(value);
    }
}    

Here, we are setting rounding mode to Up for DecimalFormat so it will round up the decimal value, whether it is greater or equal to 5 or not for the given decimal places.

Output:

Round up format: 1.0352

Round Down to x decimal places:

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

public class DecimalFormatter {

    public static void main(String[] args) {
        // round down format
        System.out.println("Round down format: " + formatRoundDown(1.0316, "0.000"));
    }
    
	private static String formatRoundDown(double value, String precision) {
        DecimalFormat df = new DecimalFormat(precision);
        df.setRoundingMode(RoundingMode.DOWN);
        return df.format(value);
    }
}    

In the above example, we are setting rounding mode to Down such that it will round down the decimal value whether it is greater or equal to 5.

Output:

Round down format: 1.031
Share: