PHP number_format: Format Decimals and Thousands

This article explains how to use the PHP number_format() function to format numbers with grouped thousands and a specific number of decimal places. You will learn the syntax of the function, see practical code examples, and understand how to customize decimal and thousands separators to match different regional or currency formats.

The number_format() function in PHP is the standard way to format numbers for presentation. It can accept one, two, or four parameters (it cannot accept three parameters).

Syntax

number_format(
    float $num,
    int $decimals = 0,
    ?string $decimal_separator = ".",
    ?string $thousands_separator = ","
): string

1. Basic Formatting (Two Parameters)

To format a number with grouped thousands and a specific number of decimal places using the default English notation (dot for decimals, comma for thousands), pass the number and the desired decimal precision as the second argument.

$number = 1234567.8912;

// Format with 2 decimal places
$formatted = number_format($number, 2);

echo $formatted; 
// Output: 1,234,567.89

The function automatically rounds the number to the nearest decimal place specified. For example, if you format 1234.567 to two decimal places, it rounds up to 1,234.57.

2. Custom Separators (Four Parameters)

If you need to use different separators—such as the French format which uses a comma for decimals and a space or dot for thousands—you must provide all four parameters.

$number = 1234567.8912;

// Format with 2 decimal places, comma for decimal, and space for thousands
$french_format = number_format($number, 2, ',', ' ');

echo $french_format; 
// Output: 1 234 567,89

Here is another example using German formatting rules, which use a comma for decimals and a dot for thousands:

$number = 1234567.8912;

// Format with 2 decimal places, comma for decimal, and dot for thousands
$german_format = number_format($number, 2, ',', '.');

echo $german_format; 
// Output: 1.234.567,89

Important Considerations