String Printf Format Specifiers

Compose fixed-width receipts and logs with printf specifiers: types, precision, width, alignment, grouping, signs, zero padding, and radices.

JavaCli Tooling

Code

snippet
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);
    }
}

How the snippet works

String Printf Format Specifiers is built around the class ReceiptFormatter and the function main.

Applying it

The demo output is labeled (%,d%n, hex:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does String Printf Format Specifiers print when run?
The script runs standalone; its 2 labeled outputs include `%,d%n`, `hex:`.