Format numerical data with printf in Java

Java 8Object Oriented ProgrammingProgramming

First, we have taken a double variable and displayed it twice.

double d = 399.8877;
System.out.printf("d1 = %2$f d2 = %1$g", d, d);

After that, we have formatted numerical int data −

int val1 = 90, val2 = 35, val3 = 88, val4 = 600;
System.out.printf("\nval1 = %d, val2 = %x, val3 = %o, val4 = %d", val1, val2, val3, val4);
System.out.printf("\nval2 = %4$d, val2 = %3$d, val3 = %2$o, val4 = %1$d", val1, val2, val3, val4);

Above, we have displayed %o for octal, %x for hexadecimal, %d for integer, etc.

The following is the complete example −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) throws Exception {
      int val1 = 90, val2 = 35, val3 = 88, val4 = 600;
      double d = 399.8877;
      System.out.printf("d1 = %2$f d2 = %1$g", d, d);
      System.out.printf("\nval1 = %d, val2 = %x, val3 = %o, val4 = %d", val1, val2, val3, val4);
      System.out.printf("\nval2 = %4$d, val2 = %3$d, val3 = %2$o, val4 = %1$d", val1, val2, val3, val4);
   } 
}

Output

d1 = 399.887700 d2 = 399.888
val1 = 90, val2 = 23, val3 = 130, val4 = 600
val2 = 600, val2 = 88, val3 = 43, val4 = 90
raja
Published on 27-Dec-2018 07:12:30
Advertisements