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 = ","
): string1. 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.89The 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,89Here 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,89Important Considerations
- Return Type: The
number_format()function returns a string, not a float or integer. This means you should only use it at the presentation layer of your application, after all mathematical calculations are complete. - Parameter Limitation: You cannot pass three parameters to this function. You must provide either one parameter (which removes all decimals), two parameters (number and decimals), or four parameters (number, decimals, decimal separator, and thousands separator).