How to round a double value in Java.
Overview
In this post, we will learn how to round a double value in Java with the help of a small program.
First, let’s perform some calculation and try to print the double variable as shown below:
/** * */ package questions; import java.util.Scanner; public class RoundDoubleExample { public static void main(String[] args) { double l; // liters double g; // gallons Scanner keyboard = new Scanner( System.in ); System.out.print( "Enter liters := " ); l = keyboard.nextDouble( ); g = 0.264 * l; System.out.print( l + " Liters = " ); System.out.println( g + " gallons." ); keyboard.close(); } }
Sample output of the program:
Enter liters := 3.785
3.785 Liters = 0.9992400000000001 gallons.
There are so many decimals printed in the output. In some cases, we may want to round the values to 2 or three decimal places. One reason could be the consistency in the output format. Lets us round the value to 3 decimal places.
Math.round()
We can round the variable to 3 decimal places by using Math.round() function.
(double)Math.round(gallons * 1000d) / 1000d
/** * */ package questions; import java.util.Scanner; public class RoundDoubleExample { public static void main(String[] args) { double l; // liters double g; // gallons Scanner keyboard = new Scanner( System.in ); System.out.print( "Enter liters := " ); l = keyboard.nextDouble( ); g = 0.264 * l; System.out.print( l + " Liters = " ); System.out.println( (double)Math.round(g * 1000d) / 1000d + " gallons." ); keyboard.close(); } }
Enter liters := 3.785
3.785 Liters = 0.999 gallons.
Using DecimalFormat
DecimalFormat df = new DecimalFormat(“0.000”);
use df.format() to display the variable to round to 3 decimal places.
/** * */ package questions; import java.text.DecimalFormat; import java.util.Scanner; public class RoundDoubleExample { private static DecimalFormat df = new DecimalFormat("0.000"); public static void main(String[] args) { double l; double g; Scanner keyboard = new Scanner( System.in ); System.out.print( "Enter liters := " ); l = keyboard.nextDouble( ); g = 0.264 * l; System.out.print( l + " Liters = " ); System.out.println( df.format(g) + " gallons." ); keyboard.close(); } }