The PHP number_format()
function is used to format a number with thousands and decimal separators.
The function syntax is as shown below:
number_format(
float $num,
int $decimals = 0,
?string $decimal_separator = ".",
?string $thousands_separator = ","
): string
The function accepts 4 parameters:
- The
float
number to format (required) - The
int
number of decimal digits in the format (optional) - The
string
for decimal separator (optional) - The
string
for thousands separator (optional)
Although the function accepts a float
type data for the number to format, it will return a string
to include the decimal and thousand separators in the number.
Hereโs how you call the function:
// ๐ no decimal format: 10,999,888
echo number_format(10999888);
// ๐ 2 decimal digits: 10,999,888.00
echo number_format(10999888, 2);
// ๐ 1 decimal digits: 10,999,888.3
echo number_format(10999888.333, 1);
// ๐ use custom separators: 10#999#888;33
echo number_format(10999888.333, 2, ";", "#");
Keep in mind that when you pass a decimal separator, you also need to pass the thousands separator.
When you pass only three parameters, the number_format()
function will generate a warning and return NULL
:
// ๐ the following call generates a warning
number_format(10999888.333, 2, ";");
// Warning: Wrong parameter count for number_format()
// in index.php on line 1
To change the thousand separator only, you still need to pass the original decimal separator value, which is a dot (.
) symbol.
Hereโs how to change only the thousand separator using number_format()
:
echo number_format(10999888.333, 0, ".", "#");
// ๐ result: 10#999#888
If youโre using PHP v8, you can also pass named arguments to skip passing $decimals
and $decimal_separator
as shown below:
echo number_format(
num: 10999888.333,
thousands_separator: "#"
);
// ๐ result: 10#999#888
And thatโs how you format a number using PHP number_format()
function.
For more information, see the PHP number_format() documentation.