How to use java system.out.printf() [transfer]

  1. public class  Main   
  2. {  
  3.     publicstaticvoid main(String[] args)    
  4.     {  
  5.         // Define some variables to format the output.  
  6.         double d = 345.678;  
  7.         String s =  "Hello!" ;  
  8.         int i = 1234;  
  9.         // "%" means formatted output, and the content after "%" is the definition of the format.  
  10.         System.out.printf( "%f" , d); // "f" means formatted output float.  
  11.         System.out.println();  
  12.         System.out.printf( "%9.2f" , d); // The 9 in "9.2" is the length of the output, and the 2 is the number of digits after the decimal point.  
  13.         System.out.println();  
  14.         System.out.printf( "%+9.2f" , d); // "+" means the output number is signed.  
  15.         System.out.println();  
  16.         System.out.printf( "%-9.4f" , d); // "-" means that the output number is left-aligned (default is right-aligned).  
  17.         System.out.println();  
  18.         System.out.printf( "%+-9.3f" , d); // "+-" means the output number is signed and left justified.  
  19.         System.out.println();  
  20.         System.out.printf( "%d" , i); // "d" means output decimal integer.  
  21.         System.out.println();  
  22.         System.out.printf( "%o" , i); // "o" ​​means output octal integer.  
  23.         System.out.println();  
  24.         System.out.printf( "%x" , i); // "d" means output hexadecimal integer.  
  25.         System.out.println();  
  26.         System.out.printf( "%#x" , i); // "d" means output an integer with a hexadecimal flag.  
  27.         System.out.println();  
  28.         System.out.printf( "%s" , s); // "d" means output string.  
  29.         System.out.println();  
  30.         System.out.printf( "Output a float: %f, an integer: %d, a string: %s" , d, i, s);  
  31.         // Multiple variables can be output, pay attention to the order.  
  32.         System.out.println();  
  33.         System.out.printf( "String: %2$s, hexadecimal number of %1$d: %1$#x" , i, s);  
  34.         // "X$" represents the number of variables.  
  35.     }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326238162&siteId=291194637