PHP number format with number_format() function

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.

More PHP tutorials

See all