In this example we will show two methods to round a number to 2 decimal places in Java.
Source Code
1) Using String.format()
package com.beginner.examples;
public class RoundExample1 {
public static void main(String[] args) {
double x1 = 0.006;
System.out.println(String.format("%.2f", x1));
double x2 = 0.002;
System.out.println(String.format("%.2f", x2));
double x3 = -0.006;
System.out.println(String.format("%.2f", x3));
double x4 = -0.002;
System.out.println(String.format("%.2f", x4));
}
}
Output:
0.01
0.00
-0.01
-0.00
2) Using java.text.DecimalFormat
package com.beginner.examples;
import java.text.DecimalFormat;
public class RoundExample2 {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("######0.00");
double x1 = 0.006;
System.out.println(df.format(x1));
double x2 = 0.002;
System.out.println(df.format(x2));
double x3 = -0.006;
System.out.println(df.format(x3));
double x4 = -0.002;
System.out.println(df.format(x4));
}
}
Output:
0.01
0.00
-0.01
-0.00
References
Imported packages in Java documentation: