”格式化说明“的格式
格式化说明最多会有5个部分(不包括%符号)。下面【】符号里面都是选择性的项目,因此只有%与type是必要的。格式化说明的顺序是有规定的,必须要以这个顺序来指定。
1、%d(参数必须能够与int相容)
format("%d",42);
结果:42
2、%f(参数必须是浮点数类型)
format("%.3f", 42.000000);
结果:42.000
3、%x(参数必须是byte、short、int、long、BigInteger)
format("%x", 42);
结果:2a
4、%c(参数同上,但不包括BigInteger)
format("%c", 42);
结果:*
5、超过一项以上的参数时:
int one = 20456654;
double two = 100567890.248907;
String s = String.format("The rank is %,d out of %,.2f", one, two);
结果:The rank is 20,456,654 out of 100,567,890.25
6、完整的日期与时间: %tc
String.format("%tc", new Date());
结果:Thu Dec 12 15:48:55 MST 2019
7、只有时间:%tr
String.format("%tr", new Date());
结果:15:48:55 PM
8、周、月、日:%tA %tB %td
Date today = new Date();
String.format("%tA, %tB %td", today, today, today);
结果:Thu,Dec 12
9、同上,但不用重复给参数
Date today = new Date();
String.format("%tA, %<tB %<td", today);
结果:Thu,Dec 12