How can the number_format or sprintf functions be used in PHP to format numbers with specific decimal precision?

To format numbers with specific decimal precision in PHP, you can use either the number_format or sprintf functions. number_format is used to format a number with grouped thousands and a specified number of decimal places, while sprintf allows for more custom formatting options. You can use number_format to round a number to a specific decimal precision, and sprintf to format a number with a specific number of decimal places.

// Using number_format to format a number with specific decimal precision
$number = 1234.56789;
$formatted_number = number_format($number, 2); // Rounds to 2 decimal places
echo $formatted_number; // Output: 1,234.57

// Using sprintf to format a number with specific decimal precision
$number = 1234.56789;
$formatted_number = sprintf("%.2f", $number); // Formats to 2 decimal places
echo $formatted_number; // Output: 1234.57