4.7.13 Pretty-printing numbers: number_format()This is NOT the latest copy of this book; click here for the latest version.
string number_format ( float number [, int decimal_places])
string number_format ( float number, int decimal_places, string decimal_point, string thousands_seperator)
Number_format() is a remarkably helpful function that takes a minimum of one parameter, the number to format, and returns that same number with grouped thousands. There are two function prototypes for number_format() as you either pass it one, two, or four parameters - passing it one or two fits the first prototype, and passing four fits the second.
So, if you pass number_format() a parameter of "1234567", it will return "1,234,567". By default, number_format() rounds fractions - 1234567.89 becomes 1,234,568. However, you can change this by specifying the second parameter, which is the number of decimal places to include. Parameter three allows you to choose the character to use as your decimal point, and parameter four allows you to choose the character to use as your thousands separator. Here is how it all looks in PHP:
<?php
$num = 12345.6789
$a = number_format($num);
$b = number_format($num, 3);
$c = number_format($num, 4, ',', '.'); ?>
After running that script, $a will be set to 12,346, $b will be set to 12,345.679, and $c will be set to 12.345,6789 (periods used to separate thousands, and commas used for the decimal point, east European-style).
As you can imagine, number_format() is incredibly useful when it comes to formatting money for checkout pages in shopping baskets, although it is useful anywhere you need to represent large numbers - adding a thousand separator invariably makes things easier to read.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|