Set Width and Precision to Format Output in Java



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
Updated on: 2019-07-30T22:30:24+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements