Let’s say we need to round number to 3 decimal places, therefore use the following format −
DecimalFormat decFormat = new DecimalFormat("0.000");
Now, format the number −
decFormat.format(37878.8989)
Since we have used the DecimalFloat class above, therefore do import the following package −
import java.text.DecimalFormat;
The following is an example that rounds a number to 3 decimal places −
import java.text.DecimalFormat; public class Demo { public static void main(String[] args) { DecimalFormat decFormat = new DecimalFormat("0.000"); System.out.println("Result = " + decFormat.format(37878.8989)); } }
Result = 37878.899
Let us see another example that rounds a number to 5 decimal places −
import java.text.DecimalFormat; public class Demo { public static void main(String[] args) { System.out.println(String.format("Result = %.5f", 76576.696799)); } }
Result = 76576.69680