Java Program to round number to fewer decimals


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 −

Example

 Live Demo

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));
   }
}

Output

Result = 37878.899

Let us see another example that rounds a number to 5 decimal places −

Example

 Live Demo

import java.text.DecimalFormat;
public class Demo {
   public static void main(String[] args) {
      System.out.println(String.format("Result = %.5f", 76576.696799));
   }
}

Output

Result = 76576.69680
raja
Published on 21-Dec-2018 11:17:15
Advertisements