How can sprintf() be used to format numbers with a specific number of decimal places in PHP?
To format numbers with a specific number of decimal places in PHP, you can use the sprintf() function. This function allows you to specify the number of decimal places by using a format specifier like "%.2f" for two decimal places. Simply pass the format specifier along with the number you want to format to sprintf() to achieve the desired result.
$number = 123.456789;
$formattedNumber = sprintf("%.2f", $number);
echo $formattedNumber; // Output: 123.46
Keywords
Related Questions
- What are the best practices for handling line breaks in text input fields when working with PHP and MySQL databases?
- What potential pitfalls should PHP developers be aware of when working with Unix timestamps and time zones?
- What potential issues can arise when using $PHP_SELF in PHP scripts for form actions?