Skip to content

下面是 String.format 常见格式化用法的表格:

格式化符号类型说明示例输出
%d整数(十进制)格式化为十进制整数String.format("%d", 42)42
%f浮点数格式化为浮点数,保留小数点后6位(默认)String.format("%f", 3.14159)3.141590
%.2f浮点数格式化为浮点数,保留两位小数String.format("%.2f", 3.14159)3.14
%e科学计数法格式化为科学计数法String.format("%e", 123456.789)1.234568e+05
%s字符串格式化为字符串String.format("%s", "Alice")Alice
%10d整数(指定宽度)输出宽度为10,默认右对齐(不足时填充空格)String.format("%10d", 42)42
%-10d整数(指定宽度左对齐)输出宽度为10,左对齐(不足时填充空格)String.format("%-10d", 42)42
%010d整数(指定宽度,填充零)输出宽度为10,右对齐,填充零String.format("%010d", 42)0000000042
%x十六进制(小写)格式化为十六进制,输出小写字母String.format("%x", 255)ff
%X十六进制(大写)格式化为十六进制,输出大写字母String.format("%X", 255)FF
%%百分比格式化为百分比,乘以100,并添加百分号String.format("%.2f%%", 0.85)85.00%
%c单个字符格式化为字符String.format("%c", 'A')A
%t%T日期时间格式化日期时间,具体格式根据类型(如%tY, %tFString.format("%tY-%tm-%td", new Date())2025-01-21
%n换行符格式化为操作系统的换行符(平台相关)String.format("Hello%nWorld")Hello World