How to Add Commas to a Number in PHP

09/07/2021
Contents
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.
Syntax:
number_format ( float $number , int $decimals = 0 , string $decimal_point = "." , string $thousands_sep = "," ) : string
Parameters:
$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 (,).
Example:
<?php
$number = 1234567;
$formatted_number = number_format($number);
echo $formatted_number;
// Output: 1,234,567
?>
Here’s an example with all the parameters:
<?php
$number = 123456.789;
$formatted_number = number_format($number, 2, '.', ',');
echo $formatted_number;
// Output: 123,456.79
?>