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 
d2 = %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("
d1 = %5.3f
d2 = %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 
d2 = %8g", d1, d2); System.out.printf("
d1 = %5.3f
d2 = %2.5f", d1, d2); } }

Output

d1 = 399.89
d2 = 298.877
d1 = 399.888
d2 = 298.87690
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements