What is the usage of number_format in PHP?

The number_format function is used to format numbers and returns the formatted string.

Syntax:
string number_format (float $number, int $decimals = 0, string $dec_point = “.”, string $thousands_sep = “,”)

parameter

  1. $number: the number to be formatted.
  2. Decimals (optional): Number of decimal places to be retained, with a default of 0.
  3. $dec_point (optional): the character used to display the decimal point, with a default setting of “.”.
  4. $thousands_sep (optional): The character that will be used as the thousands separator, default is “,”.

Return value: Return a formatted string.

示例:To make a long story short

$number1 = 123456.789;
$number2 = 987654.321;

// 格式化为带两位小数的字符串
$formattedNumber1 = number_format($number1, 2);
echo $formattedNumber1; // 输出:123,456.79

// 格式化为不带小数的字符串,并以空格作为千位分隔符
$formattedNumber2 = number_format($number2, 0, ".", " ");
echo $formattedNumber2; // 输出:987 654

In the above examples, the first call to the number_format function formats the floating-point number 123456.789 as a string “123,456.79” with two decimal places. The second call to the number_format function formats the floating-point number 987654.321 as a string “987 654” without decimals, with the thousand separator being a space.

bannerAds