PHP number_format() Function

Definition

The number_format() function rounds numbers and adds commas as a thousands separator.

Syntax

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]] )

Parameter

  • number - The number being formatted.
  • decimals - Sets the number of decimal points.
  • dec_point - Sets the separator for the decimal point.
  • thousands_sep - Sets the thousands separator.

This function accepts either one, two, or four parameters (not three):

  • If only one parameter is given, number will be formatted without decimals, but with a comma (",") between every group of thousands.
  • If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.
  • If all four parameters are given, number will be formatted with decimals decimals, dec_point instead of a dot (".") before the decimals and thousands_sep instead of a comma (",") between every group of thousands.

Return

PHP number_format() Function returns a formatted version of number.

Example

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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions