What are the differences between using printf, sprintf, and number_format to format numbers in PHP?
When formatting numbers in PHP, printf is used to output a formatted string, sprintf is used to return a formatted string, and number_format is used to format a number with grouped thousands. To format numbers using printf, you need to specify a format specifier in the string followed by the variable to be formatted. sprintf works similarly to printf but returns the formatted string instead of outputting it. number_format is specifically designed for formatting numbers with grouped thousands and allows for customization of decimal points and separators.
// Using printf to format and output a number
$number = 1234.56;
printf("Formatted number: %.2f", $number);
// Using sprintf to format a number and store it in a variable
$number = 1234.56;
$formatted_number = sprintf("%.2f", $number);
echo $formatted_number;
// Using number_format to format a number with grouped thousands
$number = 1234567.89;
$formatted_number = number_format($number, 2, '.', ',');
echo $formatted_number;