Recipe 2.10. Formatting Monetary Values


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 money_format( ) function with the %n formatting option for a national currency format:

$number = 1234.56; setlocale(LC_MONETARY, 'en_US'); print money_format('%n', $number);    // $1,234.56 

For an international format, pass %i:

print money_format('%i', $number); // USD 1,234.56

2.10.3. Discussion

The money_format( ) function formats a number by inserting the correct currency symbol, decimal, and thousands separators for your locale. It takes a formatting string and a number to format.

For easy formatting, use the %n and %i specifiers, for in-country and international standard currency displays, respectively.

To get the correct country format, change the locale, as shown in Example 2-3.

Displaying currency using standard formats

<?php $number = 1234.56; setlocale(LC_MONETARY, 'en_US'); print money_format('%n', $number);    // $1,234.56 print money_format('%i', $number);    // USD 1,234.56 setlocale(LC_MONETARY, 'fr_FR'); print money_format('%n', $number);    // 1 234,56 Eu print money_format('%i', $number);    // 1 234,56 EUR setlocale(LC_MONETARY, 'it_IT'); print money_format('%n', $number);    // Eu 1.235 print money_format('%i', $number);    // EUR  1.235 ?>

If your locale is not set, the function returns the same string you provide. For more on setting locales, see Chapter 19.

You can also use printf-like formatting options, including ( to wrap negative numbers inside of parentheses, and ! to suppress the currency symbol, as shown in Example 2-4.

Displaying currency using custom formats

<?php $number = -1234.56; setlocale(LC_MONETARY, 'en_US'); print money_format('%n', $number);    // -$1,234.56 print money_format('%(n', $number);   // ($1,234.56) print money_format('%!n', $number);   // -1,234.56 ?>

A complete list of options, including left and right precision, fill characters, and disabling grouping is available at http://www.php.net/money-format.

This function uses the underlying Unix strfmon( ) system function , so it is unavailable on Windows machines.

For more on currency formatting, including a substitute algorithm for Windows, see Recipe 19.6.

2.10.4. See Also

Recipe 19.6; documentation on money_format( ) at http://www.php.net/money-format.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

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