How to Use number_format in PHP: Syntax and Examples
Use the
number_format function in PHP to format a number with grouped thousands and decimal points. It takes the number, optional decimals count, decimal point character, and thousands separator character as arguments to customize the output.Syntax
The number_format function formats a number with grouped thousands and decimal points.
- number: The number to format.
- decimals (optional): How many decimal digits to show.
- decimal_point (optional): Character to use for the decimal point.
- thousands_separator (optional): Character to use for thousands separator.
php
string number_format(float $number, int $decimals = 0, string $decimal_point = ".", string $thousands_separator = ",")
Example
This example shows how to format a number with 2 decimals, a dot as decimal point, and a comma as thousands separator.
php
<?php $number = 1234567.891; $formatted = number_format($number, 2, '.', ','); echo $formatted; ?>
Output
1,234,567.89
Common Pitfalls
Common mistakes include:
- Not specifying decimals when you want decimal places, so the number rounds to an integer.
- Using wrong characters for decimal point or thousands separator, which can confuse readers.
- Passing non-numeric values, which causes warnings or unexpected results.
php
<?php // Wrong: no decimals, output is rounded integer $val1 = number_format(1234.56); echo $val1; // Outputs: 1,235 // Right: specify decimals to keep decimal places $val2 = number_format(1234.56, 2); echo $val2; // Outputs: 1,234.56 ?>
Output
1,235
1,234.56
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| number | The number to format | Required |
| decimals | Number of decimal digits | 0 |
| decimal_point | Decimal point character | "." |
| thousands_separator | Thousands separator character | "," |
Key Takeaways
Use number_format to add commas and decimals to numbers for better readability.
Always specify decimals if you want to keep decimal places; otherwise, it rounds to an integer.
Customize decimal and thousands separators to match your locale or style.
Avoid passing non-numeric values to prevent warnings or errors.