格式化输出
引言
如果我们简单的使用System.out.print(x)
打印输出,将会以x的类型所允许的最大非0数位个数打印输出x,例如:
double x = 1000.0 / 3.0;
System.out.print(x);
// 输出
333.3333333333333
但有时我们希望可以对输出的格式有更多的控制,这时可以通过System.out.printf()
方法实现
Java5沿用了C语言函数库的printf方法
方法
一、格式说明符语法
二、格式说明符
- 字段宽度与精度
m.n:总计打印m个字符,精度为小数点之后n个字符
- 不适用字段宽度时,将默认以能展示数值的最小宽度展示
- 使用字段宽度时,默认右对齐;如果字段宽度不够,将自动增加宽度
- 转换符(尾部)
转换符 | 类型 | 示例 |
d | 十进制整数 | 159 |
x | 十六进制整数 | 9f |
o | 八进制整数 | 237 |
f | 定点浮点数 | 15.9 |
e | 指数浮点数 | 1.59e+01 |
g | 通用浮点数(e和f中较短的一个) | — |
a | 十六进制浮点数 | 0x1.fccdp3 |
s | 字符串 | Hello |
c | 字符 | H |
b | 布尔 | true |
h | 散列码 | 42628b2 |
% | 百分号 | % |
n | 与平台有关的行分隔符 | — |
- 可以用s转换符格式化任意的对象
- 对于实现了Formattable接口的任意对象,将调用这个对象的formatTo方法
- 否则调用toString方法将这个对象转换为字符串
- 标志
标志 | 目的 | 示例 |
+ | 打印正数和负数的符号(对于负数好像并不需要) | +3333.33 |
space | 在正数之前添加空格 | | 3333.33| |
0 | 数字前面补0(数字前,符号后) | 003333.33 |
- | 左对齐(默认右对齐) | |3333.33 | |
( | 将负数括在括号里(不再打印负号) | (3333.33) |
, | 添加分组分隔符 | 3,333.33 |
#(对于f格式) | 包含小数点 | 3333. |
#(对于x或o格式) | 添加前缀0x或0 | 0xcafe |
$ | 指定要格式化的参数索引 | 159 9F |
< | 格式化前面说明的数值 | 159 9F |
部分对比示例
// 在下面的示例输出中,以'*'指代空格
// +: 打印正数和负数的符号
System.out.printf("%8d", 100); // *****100
System.out.printf("%+8d", 100); // ****+100
// space: 在正数之前添加空格
System.out.printf("%d", 100); // 100
System.out.printf("% d", 100); // *100
// 0: 数字前面补0
System.out.printf("%8d", 100); // *****100
System.out.printf("%08d", 100); // 00000100
System.out.printf("%8d", -100); // ****-100
System.out.printf("%08d", -100); // -0000100
// -: 左对齐
System.out.printf("%8d", 100); // *****100
System.out.printf("%-8d", 100); // 100*****
// (: 将负数括在括号里(不再打印负号)
System.out.printf("%8d", -100); // ****-100
System.out.printf("%(8d", -100); // ***(100)
// ,: 添加分组分隔符
System.out.printf("%12d", 333333333); // *333,333,333
System.out.printf("%,12d", 333333333); // ***333333333
// #: 包含小数点
System.out.printf("%8.0f", 3333F); // ****3333
System.out.printf("%#8.0f", 3333F); // ***3333.
// #: 添加前缀0x(对于x转换符)
System.out.printf("%8x", 100); // ******64
System.out.printf("%#8x", 100); // ****0x64
// #: 添加前缀0(对于o转换符)
System.out.printf("%8o", 100); // *****144
System.out.printf("%#8o", 100); // ****0144
// $: 指定要格式化的参数索引
System.out.printf("%1$8d %1$8x", 100); // *****100*******64
// $: 格式化前面说明的数值
System.out.printf("%8d%<8x", 100); // *****100*******64
- 参数索引值从1开始,而不是从0开始。这是为了避免与0标志混淆
- 标志之间可以组合使用,顺序并不会产生影响,例如:
System.out.printf("%#8x", 100); // ****0x64
System.out.printf("%08x", 100); // 00000064
System.out.printf("%0#8x", 100); // 0x000064
System.out.printf("%#08x", 100); // 0x000064