Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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]) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata