start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

2.10. Formatting Numbers

2.10.1. Problem

You have a number and you want to print it with thousands and decimals separators. For instance, you want to display prices for items in a shopping cart.

2.10.2. Solution

Use the number_format( ) function to format as an integer:

$number = 1234.56;
print number_format($number);    // 1,235 because number is rounded up

Specify a number of decimal places to format as a decimal:

print number_format($number, 2); // 1,234.56

2.10.3. Discussion

The number_format( ) function formats a number by inserting the correct decimal and thousands separators for your locale. If you want to manually specify these values, pass them as the third and fourth parameters:

$number = 1234.56;
print number_format($number, 2, '@', '#'); // 1#234@56

The third argument is used as the decimal point and the last separates thousands. If you use these options, you must specify both arguments.

By default, number_format( ) rounds the number to the nearest integer. If you want to preserve the entire number, but you don't know ahead of time how many digits follow the decimal point in your number, use this:

$number = 1234.56; // your number
list($int, $dec) = explode('.', $number);
print number_format($number, strlen($dec));

2.10.4. See Also

Documentation on number_format( ) at http://www.php.net/number-format.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.