← 中文资源

简体中文版本

printf 格式符速查

用 printf 格式符拼定宽输出:%s/%d/%.2f 定类型与精度,%12s 与 %-12s 控制宽度对齐,%,d 千分位、%+d 显式符号、%05d 补零、%x/%o 换进制,%n 用平台换行。

阅读英文原文

实现说明

除了类 ReceiptFormatter和函数 main,文件里再无其他定义。

使用要点

  • 跑完文件,输出里会留下标记——%,d%n、hex:。

常见问题

运行「printf 格式符速查」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 %,d%n、hex: 标签标明各步骤。

核心语句

String item = "SSD 2TB";
double price = 89.5;
int qty = 3;

代码示例

public class ReceiptFormatter {

    public static void main(String[] args) {
        String item = "SSD 2TB";
        int qty = 3;
        double price = 89.5;

        // format specifiers:%s 字符串、%d 整数、%.2f 两位小数、%n 平台换行
        System.out.printf("%s x %d = %.2f EUR%n", item, qty, price);

        // 宽度与对齐:%12s 右对齐占 12 列,%-12s 左对齐补空格
        System.out.printf("%12s | %-12s%n", "right", "left");

        // 千分位分组与显式符号
        System.out.printf("%,d%n", 12_345_678);
        System.out.printf("%+d%n", 42);

        // 补零与进制:编号、时间戳场景常用
        System.out.printf("%05d%n", 42);
        System.out.printf("hex: %x  octal: %o%n", 255, 255);
    }
}