- 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.
- package com.javarounddecimal;
- import java.text.DecimalFormat;
- public class RoundDecimal {
- /**
- * java round double to 2 decimal places
- * @author www.instanceofjava.com
- */
- public static void main(String[] args) {
- double number = 12.3712377;
- DecimalFormat df1 = new DecimalFormat("#.##");
- System.out.println(number + " is rounded to: " + df1.format(number));
- DecimalFormat df2 = new DecimalFormat("#.###");
- System.out.println(number + " is rounded to: " + df2.format(number));
- number = 12.388654;
- DecimalFormat df3 = new DecimalFormat("#.##");
- System.out.println(number + " is rounded to: " + df3.format(number));
- DecimalFormat df4 = new DecimalFormat("#.###");
- System.out.println(number + " is rounded to: " + df4.format(number));
- }
- }
- 12.3712377 is rounded to: 12.37
- 12.3712377 is rounded to: 12.371
- 12.388654 is rounded to: 12.39
- 12.388654 is rounded to: 12.389
Java Program to round float number to 2 / 3 decimal places.
Output:
- 12.371238 is rounded to: 12.37
- 12.371238 is rounded to: 12.371
- 12.388654 is rounded to: 12.39
- 12.388654 is rounded to: 12.389
No comments