» » Java example program to round double to 2 decimal places

  • To round the decimal number in java we have DecimalFormat class in java.
  • By using DecimalFormat class format() method we can round double or float number to N decimal places.
  • Lets see a java program on how to round double to 2 decimal places.



 Java Program to round double number to 2 / 3 decimal places.


  1. package com.javarounddecimal;
  2. import java.text.DecimalFormat;
  3.  
  4. public class RoundDecimal {
  5.     /**
  6.      * java round double to 2 decimal places
  7.      * @author www.instanceofjava.com
  8.      */
  9.     public static void main(String[] args) {
  10.         
  11.         double number = 12.3712377;
  12.         DecimalFormat df1 = new DecimalFormat("#.##");
  13.         System.out.println(number + " is rounded to: " + df1.format(number));
  14.          
  15.         DecimalFormat df2 = new DecimalFormat("#.###");
  16.         System.out.println(number + " is rounded to: " + df2.format(number));
  17.          
  18.         number = 12.388654;
  19.         
  20.         DecimalFormat df3 = new DecimalFormat("#.##");
  21.         System.out.println(number + " is rounded to: " + df3.format(number));
  22.        
  23.         
  24.         DecimalFormat df4 = new DecimalFormat("#.###");
  25.         System.out.println(number + " is rounded to: " + df4.format(number));
  26.  
  27.     }
  28.  
  29. }
 Output:


  1. 12.3712377 is rounded to: 12.37
  2. 12.3712377 is rounded to: 12.371
  3. 12.388654 is rounded to: 12.39
  4. 12.388654 is rounded to: 12.389

  Java Program to round float number to 2 / 3 decimal places.


java round float to 2 decimal places




Output:

  1. 12.371238 is rounded to: 12.37
  2. 12.371238 is rounded to: 12.371
  3. 12.388654 is rounded to: 12.39
  4. 12.388654 is rounded to: 12.389

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu