2.10 Formatting Numbers


You want to output a number with commas in the correct places.

Technique

Use PHP's built-in number_format() function:

 <?php $num = 12500000.8356; $num = number_format ($num, 2); ?> 

Comments

The number_format() function is another place where PHP makes your life easier. In other languages (C, Perl, and so on) you would have to write your own. Although it's not that hard to create a number formatting function, in PHP, we do it for you.

The number_format() function takes either one, two, or four (not three) arguments. If one argument is specified, the number has commas inserted in the proper places. If two arguments are provided, something like this

 $num = number_format ($num, $decimal_places); 

then number_format() rounds to the number of specified decimal places. (The number $num in all cases must be a float.) If four arguments are specified, like so

 $num = number_format($num,                      $decimal_places,                      $decimal_identifier,                      $thousands_separator); 

then the number is rounded to $decimal_places , $thousands_separator is inserted in the place of commas between every group of thousands, and $decimal_identifier is placed before the decimals instead of a period.

This function is extremely useful because most of the time your users want to see data in human terms not in computer terms. The number_format() function enables you to clean up your data.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net