Java如何格式化输出

Published on 2017 - 02 - 19

基本数据类型格式化

Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted: f is a floating-point number, s a string, and d a decimal integer. Table 3.5 shows all conversion

给格式化添加额外的修饰

In addition, you can specify flags that control the appearance of the formatted output.

System.out.printf("%,.2f", 10000.0 / 3.0);

时间格式化

格式化特性

It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the %, and it must be terminated by a $. For example,

System.out.printf("%1$s %2$tB %2$te, %2$tY", "Due date:", new Date());
prints
Due date: February 9, 2004

批注:格式化时,是从1开始计数,而不是0

Reference