PHP Internationalization and Localization
Localizing Currency Values
Problem
You want to display currency amounts in a locale-specific format.
Solution
For default formatting inside a message, use the currency style of the number argument type:
$income = 5549.3;
$debit = -25.95;
$fmt = new MessageFormatter('en_US',
'{0,number,currency} in and {1,number,currency} out');
print $fmt->format(array($income,$debit));
This prints:
$5,549.30 in and -$25.95 out
For more specific formatting, use the formatCurrency() method of a NumberFormatter:
$income = 5549.3;
$debit = -25.95;
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
print $fmt->formatCurrency($income, 'USD') . ' in and ' .
$fmt->formatCurrency($debit, 'EUR') . ' out';
This prints:
$5,549.30 in and -€25.95 out
Discussion
The currency style of the number argument type in MessageFormatter uses the default currency and formatting rules for the locale of the MessageFormatter instance. This is certainly a concise and easy way to include local currency amounts in messages you are producing. The code that uses MessageFormatter prints:
$5,549.30 in and -$25.95 out
The formatCurrency() method of NumberFormatter makes it easy to specify other currencies. In the example that uses NumberFormatter, because the first call to format Currency() specifies USD (for US dollars) as the currency and the second specifies EUR (for Euro), the code prints:
$5,549.30 in and -€25.95 out
Although you can construct complex currency formatting rules with the decimal format patterns that MessageFormatter understands, it is often clearer to express those needs via the programmatic interface NumberFormatter provides. For example:
$amounts = array( array(152.9, 'USD'),
array(328, 'ISK'),
array(-1, 'USD'),
array(500.53, 'EUR') );
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setAttribute(NumberFormatter::PADDING_POSITION,
NumberFormatter::PAD_AFTER_PREFIX);
$fmt->setAttribute(NumberFormatter::FORMAT_WIDTH, 15);
$fmt->setTextAttribute(NumberFormatter::PADDING_CHARACTER, ' ');
foreach ($amounts as $amount) {
print $fmt->formatCurrency($amount[0], $amount[1]) . "\n";
}
This prints out a table of four values in different currencies, inserting enough padding between the currency symbol and the value to make each line 15 characters wide. The padding character used is a space, not the default of *. This displays:
$ 152.90
ISK 328
-$ 1.00
€ 500.53
No comments:
Post a Comment