php-girl-white-strap-top3Large numbers aren’t quite so easy for the human brain to read. Our brains tend to like breaking things up into smaller chunks to better handle them, and thus when it comes to large numbers, the simplest solution is to simply group thousands together, achieved with something known simply as a “thousands separator”.

Now the simplest way to add a thousands separator to your displayed numbers when coding in PHP is to make use of the built in PHP number_format functionality. This means that turning 45317 into a more recognisable 45,317 is nothing more than a simple function call away!

The number_format function accepts either 1, 2 or 4 parameters:

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

From the documentation:

“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.”

In action:

$number = 1234.534;
echo number_format($number);
//1,234
echo number_format($number,2);
//1,234.53
echo number_format($number,2,'+','-');
//1-234+53

Pretty useful.

Related Link: http://php.net/manual/en/function.number-format.php