The number_format() function rounds numbers and adds commas as a thousands separator.
PHP number_format() Function has the following syntax.
string number_format ( float $number [, int $decimals = 0 ] )
or
string number_format ( float num [, int decimals [, string decimal_point, string thousands_sep]] )
This function accepts either one, two, or four parameters (not three):
PHP number_format() Function returns a formatted version of number.
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:
<?PHP $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:
<?PHP 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:
<?PHP 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.
The following code shows how to format a number with grouped thousands.
<?php $number = 1234.56; // english notation (default) $english_format_number = number_format($number); echo $english_format_number; // French notation $nombre_format_francais = number_format($number, 2, ',', ' '); echo $nombre_format_francais; $number = 1234.5678; // english notation without thousands separator $english_format_number = number_format($number, 2, '.', ''); echo $english_format_number; // 1234.57 ?>
The code above generates the following result.