Formatting Currency Values

Jun 18, 2009 Author: Developer

Currency formatting, unlike number formatting, is locale aware and will display the correct currency symbol (either international or national notations—e.g.: USD or $, respectively) depending on how your locale is set. When using money_format(), we must specify the formatting rules we want to use by passing the function a specially-crafted string that consists of a percent symbol (%) followed by a set of flags that determine the minimumwidth of the resulting output, its integer and decimal precision and a conversion character that determines whether the currency value is formatted using the locale’s national or international rules.

IMPORTANT:The money_format() function is not available on Windows, as well as on some variants of UNIX. For example, to output a currency value using the American national notation with two decimal places, we’d use the following function call:

setlocale(LC_MONETARY, "en_US");
echo money_format(’%.2n’, "100000.698");

This example displays “$100,000.70”. If we simply change the locale to Japanese, we can display the number in Yen.

setlocale(LC_MONETARY, "ja_JP.UTF-8");
echo money_format(’%.2n’, "100000.698");

This time, the output is “¥100,000.70”. Similarly, if we change our formatting to use the i conversion character, money_format() will produce its output using the international notation, for example:

setlocale(LC_MONETARY, "en_US");
echo money_format(’%.2i’, "100000.698");
setlocale(LC_MONETARY, "ja_JP");
echo money_format(’%.2i’, "100000.698");

The first example displays “USD 100,000.70”, while the second outputs “JPY 100,000.70”. As you can see, money_format() is a must for any international commerce site that acceptsmultiple currencies, as it allows you to easily display amounts in currencies that you are not familiar with. There are two important things that you should keep in mind here. First, a call to setlocale() affects the entire process inside which it is executed, rather than the individual script. Thus, you should be careful to always reset the locale whenever you need to performa formatting operation, particularly if your application requires the use of multiple locales, or is hosted alongside other applications that may. In addition, you should keep in mind that the default rounding rules change from locale to locale. For example, US currency values are regularly expressed as dollars and cents, while Japanese currency values are represented as integers. Therefore, if you don’t specify a decimal precision, the same value can yield very different localedependent formatted strings:

setlocale(LC_MONETARY, "en_US");
echo money_format(’%i’, "100000.698");
setlocale(LC_MONETARY, "ja_JP");
echo money_format(’%i’, "100000.698");

The first example displays “USD 100,000.70”; however, the Japanese output is now “JPY 100,001”—as you can see, this last value was rounded up to the next integer.


views 3568
  1. Add New Comment