Menu

PHP sprintf(): Format Strings, Padding and Decimals

sprintf() builds a string from a format and values: sprintf('%05.2f', 3.14159) returns "03.14". Learn %s, %d and %f, zero padding, fixed decimals, alignment, argument numbering, printf and vsprintf.

This page includes runnable editors - edit, run, and see output instantly.

sprintf() returns a string built from a format and a list of values: each % placeholder in the format is replaced by the next value. sprintf('%s is %d years old', 'Ada', 36) returns "Ada is 36 years old". printf() takes the same arguments but prints the result instead of returning it.

The placeholders are filled in order, left to right. %.2f always shows two decimals (4.50, not 4.5), and %05d pads the number with zeros to five digits.

The format specifiers

A placeholder is %, optional modifiers, then one letter for the type:

SpecifierMeaningsprintf(...)Result
%sstringsprintf('%s', 'PHP')PHP
%dinteger (signed)sprintf('%d', 42.9)42
%ffloat, 6 decimals by defaultsprintf('%f', 1.5)1.500000
%.2ffloat, 2 decimalssprintf('%.2f', 1.5)1.50
%escientific notationsprintf('%e', 1234.5678)1.234568e+3
%x / %Xhexadecimalsprintf('%x', 255)ff
%ooctalsprintf('%o', 8)10
%bbinarysprintf('%b', 5)101
%ccharacter from a codesprintf('%c', 65)A
%uunsigned integersprintf('%u', 3)3
%%a literal percent signsprintf('%d%%', 50)50%

Change the values below and run it again:

%d truncates a float toward zero, so 42.9 becomes 42. If you want 43, round first: sprintf('%d', round(42.9)). A string that is not a number, such as 'abc', becomes 0 under %d.

Pad with leading zeros

Between % and the letter you can put a padding character and a width. %05d means "pad with 0 to a width of 5". This is the usual way to format order numbers, invoice IDs, times and dates.

The width is a minimum. A number longer than the width is printed in full.

%05.2f: width and decimals together

With floats, the width counts every character of the result, including the decimal point and the minus sign. That is why %05.2f on 3.14159 gives 03.14: five characters in total, two of them after the point.

%f uses the current locale's decimal point (set with setlocale()), while %F always uses a dot. If your code sets a locale and you need a dot for JSON, CSV or an API, use %F.

Align text in columns

A positive width right-aligns, a - before the width left-aligns, and ' followed by a character sets a custom padding character. Combined, they line up plain-text reports and receipts.

%-14s pads the item name on the right to 14 characters, %8.2f right-aligns the price in 8 characters, and %'-27s with an empty string prints a line of 27 dashes. %'*10s pads with * instead of spaces.

Number the arguments to reuse or reorder them

%1$s means "the first argument as a string", %2$d "the second as an integer". Numbered placeholders let you use a value twice or change the order without changing the argument list, which translators need when word order differs between languages.

vsprintf, printf and the return values

vsprintf() takes the values as one array, which is handy when they already sit in an array. printf() returns the number of bytes it printed, and vprintf() is the array version of printf().

The count from printf() includes the newline, so "Hello\n" is 6 bytes. For multibyte text it counts bytes, not characters.

Too few arguments throws an error

Since PHP 8, a format with more placeholders than values throws an ArgumentCountError instead of returning false. Count the % placeholders (ignoring %%) when you see this error.

The message counts the format string as an argument: ArgumentCountError: 4 arguments are required, 3 given. Extra arguments are ignored silently, so the opposite mistake does not show up as an error. If a sprintf result looks wrong, print the format next to the values. When all you need is a thousands separator, number_format() is simpler than building one with sprintf. The full list of modifiers is on php.net.

Frequently Asked Questions

How do I add leading zeros to a number in PHP?

Use sprintf('%05d', 42), which returns "00042". The 0 is the padding character and 5 is the total width. For a string, str_pad('42', 5, '0', STR_PAD_LEFT) gives the same result.

How do I format a number to 2 decimal places with sprintf?

Use %.2f: sprintf('%.2f', 3.14159) returns "3.14" and sprintf('%.2f', 5) returns "5.00". Add a width to pad it as well: %08.2f gives "00003.14".

What is the difference between printf and sprintf in PHP?

sprintf() returns the formatted string so you can store it. printf() prints it straight away and returns the number of bytes printed. echo sprintf(...) and printf(...) produce the same output.

What does %s mean in PHP?

%s is a placeholder for a string in sprintf() and printf(): sprintf('Hello, %s', 'Ada') returns "Hello, Ada". Numbers passed to %s are converted to strings. %d is for integers and %f for floats.

How do I use the same argument twice in sprintf?

Number the placeholders: sprintf('%1$s loves %2$s, and %2$s loves %1$s', 'Ada', 'PHP'). Use single quotes around the format: inside double quotes PHP reads $s as a variable, so "%1$s" becomes %1 followed by the value of $s.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED