2.9. Formatting Numbers

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.

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

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));

See Also

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

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.