printf and Formatting

Formatting with printf and number_format

sprintf() returns a formatted string, printf() prints it, vsprintf() takes an array, and sscanf() parses values back out. A placeholder is %[argnum$][flags][width][.precision]specifier: specifiers s d f x o b c e %; flags - (left-align), + (sign), 0 or '* (pad character); %2$s picks the second argument.

Aligned columns, specifiers and number formatting (format.php)PHP
<?php
$rows = [['Dune', 2, 9.5], ['The Hobbit: There and Back', 1, 12.25]];
foreach ($rows as [$title, $qty, $price]) {
    printf("%-12.12s|%4d|%9.2f\n", $title, $qty, $price);
}
echo sprintf('%05d %+d %x %o %b %c %.2e %%', 42, 7, 255, 8, 5, 65, 12345.678), ' ',
    sprintf("%'*8s|%-6s|", 'right', 'left'), "\n";
echo sprintf('%2$s has %1$d books; %2$s reads', 3, 'Ada'), ' ',
    vsprintf('%04d-%02d-%02d', explode('-', '2026-9-3')), "\n";
echo number_format(1234567.891), ' ', number_format(1234567.891, 2), ' ',
    number_format(1234567.891, 2, ',', '.'), ' ', number_format(1234567.891, -3), "\n";
Output
Dune        |   2|     9.50
The Hobbit: |   1|    12.25
00042 +7 ff 10 101 A 1.23e+4 % ***right|left  |
Ada has 3 books; Ada reads 2026-09-03
1,234,568 1,234,567.89 1.234.567,89 1,235,000

%-12.12s pads and truncates, and numbered arguments let translators reorder words. number_format() rounds half up; a negative precision (PHP 8.3) rounds to thousands. It knows no locales, so format money with intl: (new NumberFormatter('de_DE', NumberFormatter::CURRENCY))->formatCurrency(1234.5, 'EUR') returns 1.234,50 €. Widths count bytes; pad text with mb_str_pad().