Skip to content
PHP Logo

What is the function sprintf() used for in PHP and how can it help in formatting numbers?

The sprintf() function in PHP is used to format strings, including numbers, based on a specified format. It can be used to control the precision, padding, and alignment of numbers in the output string. This can be particularly useful when displaying numbers in a specific format, such as currency or decimal places.

php
$number = 123.456;
$formatted_number = sprintf("%.2f", $number);
echo $formatted_number; // Output: 123.46