How can the sprintf function in PHP be utilized for number formatting purposes?
When you need to format numbers in PHP, you can use the sprintf function to control the output format. This function allows you to specify the number of decimal places, add commas for thousands separators, and format numbers as currency. By using placeholders in the format string, you can insert variables into the formatted string.
$number = 123456.789;
// Format the number with 2 decimal places
$formattedNumber = sprintf("%.2f", $number);
echo $formattedNumber; // Output: 123456.79
// Format the number with commas as thousands separators
$formattedNumber = sprintf("%'.2f", $number);
echo $formattedNumber; // Output: 123,456.79
// Format the number as currency
$formattedNumber = sprintf("$%.2f", $number);
echo $formattedNumber; // Output: $123456.79