PHP Reference ยท String Functions
PHP number_format() function
Reference for PHP number_format(): format numbers with thousands separators and decimals, custom separators, rounding, negative zero and money pitfalls.
number_format() turns a number into a human-readable string with grouped thousands and a fixed number of decimal places. It rounds the value, so number_format(1234.567, 2) gives 1,234.57. You can choose the decimal separator and the thousands separator, which makes it easy to produce European styles such as 1.234,57.
The result is a string meant for display. Do not do arithmetic with it, and do not store it: keep the original number and format it only when you show it.
<?php echo number_format(1234567.891); // 1,234,568 echo number_format(1234567.891, 2); // 1,234,567.89
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
number_format( float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = "," ): string
| Name | Description |
|---|---|
$num |
The number to format. |
$decimals |
Digits after the decimal point. Default 0. Negative values round to the left of the point (PHP 8.3+). |
$decimal_separator |
String placed before the decimals. null means ".". |
$thousands_separator |
String placed between groups of three digits. null means ",". Use "" for none. |
Return value: the formatted string.
Errors: a TypeError if $num is not numeric.
Usage notes
- It rounds. Rounding is half away from zero on the decimal value, so
number_format(2.5)andnumber_format(1.5)give3and2. - No
-0. Since PHP 8.0, a result that rounds to zero is printed as0, not-0. - Always groups by three. It cannot produce Indian digit grouping (12,34,567) or other locale rules. For real localization use
NumberFormatterfrom theintlextension, which this site's runner does not include. - Separators can be any string. Multi-character separators work, including an HTML entity such as
(escape for the context you print in). - Money. Floats cannot represent most decimal fractions exactly. Store prices as integer cents, and format with
number_format($cents / 100, 2)at the last moment. - Do not parse the result.
"1,234.50" + 1is not 1235.5. Convert before formatting. - For padding and alignment combine it with
str_pad()or%swidths insprintf();sprintf("%.2f")has no thousands separator.
Related
sprintf(),printf(),str_pad()- Lessons: Formatting strings, Numbers, Math functions