SyntaxStudy
Sign Up
PHP Formatting Strings & Numbers
PHP Beginner 7 min read

Formatting Strings & Numbers

When you need fine-grained control over output format, sprintf() and number_format() are your best tools.

  • sprintf() returns a formatted string using format specifiers like %s (string), %d (integer), %f (float), %02d (zero-padded integer).
  • printf() is the same but prints directly.
  • number_format() formats a number with grouped thousands and decimal precision.
Example
<?php
// sprintf — build a string
$name  = 'Alice';
$score = 97.5;
$msg   = sprintf('Player %s scored %.1f points', $name, $score);
echo $msg; // Player Alice scored 97.5 points

// Zero-padding integers (useful for dates/IDs)
echo sprintf('Order #%05d', 42);   // Order #00042

// printf — print directly
printf('Price: $%.2f', 9.9);       // Price: $9.90

// number_format(number, decimals, dec_point, thousands_sep)
echo number_format(1234567.891, 2);         // 1,234,567.89
echo number_format(1234567.891, 2, '.', ','); // 1,234,567.89
echo number_format(1234567.891, 2, ',', '.'); // 1.234.567,89 (European)
Pro Tip

Tip: Use argument swapping in sprintf() for translatable strings: sprintf('%1$s owes %2$s', $debtor, $amount) lets translators reorder the arguments without touching PHP code.