HowTo – Using PHP number_format() To Add Commas To Numbers

Filed under: Web Design

Sometimes when dealing with output from your database or other numbers you are processing you will want to format the number in a readable comma separated value.

This is very simple to do with PHP by using the number_format() function.

simply find the number where ever you are reading it from and store it in a var.

[php]<?php $myrawnumber="123456" ; ?>[/php]

then you can process your raw number with the number_format()

[php]

<?php $myreadablenumber = number_format($myrawnumber);

echo $myreadablenumber;

?>

[/php]

the result should be 123,456

This is the simplest use of the number_format() you can also define the separator character to something other then a comma if necessary and you can set the place at which the comma is inserted.. normally its every third place left of the decimal but you could alter that if you need to.

Here is an extended description

Description

string number_format ( float $number [, int $decimals = 0 ] )
string number_format ( float $number , int $decimals = 0 , string $dec_point = ‘.’ , string $thousands_sep = ‘,’ )

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.