Set width and precision to format output in Java

Java 8Object Oriented ProgrammingProgramming

Set width in output as shown below. Here, %10 sets a 10 character field

System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);

Above, the value after the decimal is for decimal places i.e. 5.3 is for 3 decimal places −

System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);

The following is an example −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) throws Exception {
      double d1 = 399.8877;
      double d2 = 298.87690;
      System.out.printf("d1 = %10.2f \nd2 = %8g", d1, d2);
      System.out.printf("\nd1 = %5.3f \nd2 = %2.5f", d1, d2);
   }
}

Output

d1 = 399.89
d2 = 298.877
d1 = 399.888
d2 = 298.87690
raja
Updated on 30-Jul-2019 22:30:24

Advertisements