16.6. Localizing Currency Values
Problem
You want to display currency amounts in a locale-specific format.
Solution
Use the pc_format_currency( )
function, shown in Example 16-1, to produce an appropriately formatted string.
For example:
setlocale(LC_ALL,'fr_CA');
print pc_format_currency(-12345678.45);
(12 345 678,45 $)
Discussion
The pc_format_currency( )
function, shown in Example 16-1, gets the currency formatting information from
localeconv( )
and then uses number_format( )
and some logic to construct the correct string.
Example 16-1. pc_format_currency
function pc_format_currency($amt) { // get locale-specific currency formatting information $a = localeconv(); // compute sign of $amt and then remove it if ($amt < 0) { $sign = -1; } else { $sign = 1; } $amt = abs($amt); // format $amt with appropriate grouping, decimal point, and fractional digits $amt = number_format($amt,$a['frac_digits'],$a['mon_decimal_point'], $a['mon_thousands_sep']); // figure out where to put the currency symbol and positive or negative signs $currency_symbol = $a['currency_symbol']; // is $amt >= 0 ? if (1 == $sign) { $sign_symbol = 'positive_sign'; $cs_precedes = 'p_cs_precedes'; $sign_posn = 'p_sign_posn'; $sep_by_space = 'p_sep_by_space'; } else { $sign_symbol = 'negative_sign'; $cs_precedes = 'n_cs_precedes'; $sign_posn = 'n_sign_posn'; $sep_by_space = 'n_sep_by_space'; } if ($a[$cs_precedes]) { if (3 == $a[$sign_posn]) { $currency_symbol = $a[$sign_symbol].$currency_symbol; } elseif (4 == $a[$sign_posn]) ...
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.