2.10.1. ProblemYou 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. SolutionUse 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. DiscussionThe 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
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
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 AlsoRecipe 19.6; documentation on money_format( ) at http://www.php.net/money-format. |