What is the purpose of number_format in PHP?
The number_format function is used to format numbers, it can convert a number to a string with thousand separators, decimal points, and a specified number of decimal places.
The syntax of the number_format function is as follows:
string number_format(float $number, int $decimals = 0, string $decPoint = “.”, string $thousandsSep = “,”)
Explanation of Parameters:
- $number: the number that needs to be formatted
- $decimals: specifies the number of decimal places to be kept, defaulting to 0.
- $decPoint: Specify the character for the decimal point, default is “.”
- $thousandsSep: Specifies the character for the thousands separator, default is “,”.
示例:The teacher emphasized the importance of completing homework on time.
$number = 12345.6789;
echo number_format($number, 2); // 输出:12,345.68
$number = 123456.789;
echo number_format($number, 2, ",", "."); // 输出:123.456,79
In the above example, the number_format function formats the numbers into a string with thousand separators, as specified with the desired decimal places, decimal point, and thousand separators.