Converter description:
%s string type
%c character type
%b boolean type
%d integer type (decimal)
%x integer type (hexadecimal)
%o integer type (octal)
%f floating point type
%a hex floating point type
%e exponent type
%g generic floating point type (the shorter of the f and e types)
%h hash code
%% percent type
%n newline
%tx date and time type (x represents a different date and time converter
Example
System.out.printf("字符串类型: %s %s %s %n", "周杰伦", "林俊杰", "张学友");
System.out.printf("字符类型: %c 只能输入一个字符 %n", 'a');
System.out.printf("布尔类型: %b %n", true);
System.out.printf("整数类型(十进制): %d %n", 10);
System.out.printf("整数类型(十六进制): %x %n", 10);
System.out.printf("整数类型(八进制): %o %n", 10);
System.out.printf("浮点类型: %f %n", 10.0);
System.out.printf("十六进制浮点类型: %a %n", 10.0);
System.out.printf("指数类型: %e %n", 10.0);
System.out.printf("通用浮点类型(f和e类型中较短的): %g %n", 10.0);
System.out.printf("散列码: %h %n", 10.0);
System.out.printf("百分比类型: %d%% %n", 10);
Output result:
字符串类型: 周杰伦 林俊杰 张学友
字符类型: a 只能输入一个字符
布尔类型: true
整数类型(十进制): 10
整数类型(十六进制): a
整数类型(八进制): 12
浮点类型: 10.000000
十六进制浮点类型: 0x1.4p3
指数类型: 1.000000e+01
通用浮点类型(f和e类型中较短的): 10.0000
散列码: 40240000
百分比类型: 10%
Flags with converters
+ Add sign 0 for positive or negative numbers with 0 spaces in front of numbers Add specified number of spaces before integers , "," to group numbers ( negative numbers are enclosed in parentheses # If it is a floating point number, it includes a decimal point, if it is hexadecimal or In octal, add 0x or 0 < format the parameter described by the previous converter $ formatted parameter index
System.out.printf("\"+\": %+d %n",10);
System.out.printf("\"0\": %04d %n",10);
System.out.printf("\"空格\" % 4d %n",10);
System.out.printf("\",\": %,f %n",1000000.0);
System.out.printf("\"(\": %(f %n",-100.00);
System.out.printf("\"#\": %#x %n",10);
System.out.printf("\"<\": %f和%<1.2f %n",10.223);
System.out.printf("\"$\": %1$d %2$s %n",13,"a");
Output result:
"+": +10
"0": 0010
"空格" 10
",": 1,000,000.000000
"(": (100.000000)
"#": 0xa
"<": 10.223000和10.22
"$": 13 a
Date and event string formatting
cIncludes all date and time information
F "Year-Month-Day" format
D "Month/Day/Year" format
r "HH:MM:SS PM" format (12-hour clock)
T "HH:MM:SS" format ( 24-hour)
R "HH:MM" format (24-hour)
Date date = new Date();
System.out.printf("%tc %n", date);
System.out.printf("%tF %n", date);
System.out.printf("%tD %n", date);
System.out.printf("%tT %n", date);
System.out.printf("%tR %n", date);
System.out.printf("%tF %tT %n",date,date);
Output result:
星期日 十二月 17 16:15:39 CST 2017
2017-12-17
12/17/17
16:15:39
16:15
2017-12-17 16:15:39