Name
number_format()
Synopsis
string number_format ( floatnum
[, intdecimals
[, stringdecimal_point
, stringthousands_sep
]] )
The number_format()
function rounds numbers and adds commas as a thousands separator. You can pass it either one, two, or four parameters:
number_format($n)
rounds$n
to the nearest whole number and adds commas in between thousands. For example:$total = 12345.6789; echo "Total charge is \$", number_format($total), "\n";
That will output
Total charge is $12,346
, because it rounds up to the nearest decimal place.number_format($n,$p)
rounds$n
to$p
decimal places, adding commas between thousands. For example:echo "Total charge is \$", number_format($total, 2), "\n";
This time the output is
12,345.68
, as it has been rounded to two decimal places.number_format($n, $p, $t, $d)
rounds$n
to$p
decimal places, using$t
as the thousands separator and$d
as the decimal separator. For example:echo "Total charge is ", number_format($total, 2, ".", ","), " Euros";
The output is now
12.345,68
, which swaps the period and comma, as is the norm in many European countries.
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.