String Printf Format Specifiers
Compose fixed-width receipts and logs with printf specifiers: types, precision, width, alignment, grouping, signs, zero padding, and radices.
Code
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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- What does String Printf Format Specifiers print when run?
- The script runs standalone; its 2 labeled outputs include `%,d%n`, `hex:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.