Sometimes while working with double and floats, we need to round them to specific decimal points for calculation. For example, stores round final price to 2 decimal places with half-up rounding mode.
Example #1
Input : 12
output : 12.00
Example #2
Input: 18.888
output : 18.89
1. This example using console input with double
import java.text.DecimalFormat; import java.util.Scanner; public class Hello { private static DecimalFormat decimalFormat = new DecimalFormat(".00"); public static void main(String ar[]) { System.out.print("Please enter number : "); Scanner in = new Scanner(System.in); double number = in.nextDouble(); double roundOff = (double) Math.round(number * 100) / 100; String ns = decimalFormat.format(roundOff); System.out.println("Round off number up to 2 decimal place : " + ns); } }
Outputs
Test #1
Please enter number : 12
Round off number up to 2 decimal place : 12.00Test #2
Please enter number : 18.888
Round off number up to 2 decimal place : 18.89
2. Using float variable
import java.text.DecimalFormat; public class Hello { private static DecimalFormat decimalFormat = new DecimalFormat(".00"); public static void main(String ar[]) { float number = 24.989f; float roundOff = (float) Math.round(number * 100) / 100; String ns = decimalFormat.format(roundOff); System.out.println("Round off number up to 2 decimal place : " + ns); } }
A. Formula of example is to round of up to 2 decimal points
Round off
double roundOff = (double) Math.round(number * 100) / 100;
Formate
private static DecimalFormat decimalFormat = new DecimalFormat(".00");
B. Formula of example is to round of up to 3 decimal points
Round off
double roundOff = (double) Math.round(number * 1000) / 1000;
Formate
private static DecimalFormat decimalFormat = new DecimalFormat(".000");
Uses : Sometimes in project we needed show pricing in $189.00 or ₹123.00 format.
It can be also interview question for Java and android developers.
Thank you Rohit! This was very helpful.