How to Add Commas to a Number in PHP



In this article, you will learn how to add commas to a number in PHP.

Using number_format() function

You can add commas to a number in PHP using the number_format() function.

The number_format function in PHP can be used to format a number with decimal places and thousands separators.

number_format ( float $number , int $decimals = 0 , string $decimal_point = "." , string $thousands_sep = "," ) : string
  • $number: The number to be formatted.
  • $decimals (optional): The number of decimal places to round to. The default value is 0.
  • $decimal_point (optional): The character used to represent the decimal point. The default value is a period (.).
  • $thousands_sep (optional): The character used to separate thousands. The default value is a comma (,).
  $number = 1234567;
  $formatted_number = number_format($number);

  echo $formatted_number;
  // Output: 1,234,567

Here’s an example with all the parameters:

  $number = 123456.789;
  $formatted_number = number_format($number, 2, '.', ',');

  echo $formatted_number;
  // Output: 123,456.79