Skip to content
PHP Logo

How can the sprintf or number_format functions in PHP help in formatting numbers for display?

When displaying numbers in PHP, it is often necessary to format them in a specific way, such as adding commas for thousands separators or rounding to a certain number of decimal places. The sprintf function allows you to format a number using a specified format string, while the number_format function specifically formats a number with grouped thousands and decimal point.

php
// Using sprintf to format a number with 2 decimal places
$number = 1234.5678;
$formatted_number = sprintf("%.2f", $number);
echo $formatted_number;

// Using number_format to format a number with thousands separator and 2 decimal places
$number = 1234567.89;
$formatted_number = number_format($number, 2);
echo $formatted_number;