Home > Uncategorized > Perl Currency Formatting with International Formats

Perl Currency Formatting with International Formats

December 21st, 2004

Some notes on currency formatting, in particular adding decimal commas and automatically getting the right decimal character with printf / sprintf:

The Perl Cookbook has a good ‘commify’ starter script that can be modified in order to pass in a separator and decimal character. Just remember that in regex, you might need to add a slash in front of the character to use vars in the pattern matches.

http://www.unix.org.ua/orelly/perl/cookbook/ch02_18.htm

But before you commify something, you should use Perl’s setlocale (man setlocale) function before your printf. There are multiple LC* locale settings that you can use, but for currency, you’ll want printf to automatically use the right decimal point formatting based on the LCNUMERIC locale.

The locales installed on your box can be found by using locale -a. Personally, I find it useful to store the ones you want to support in a hash, indexed by your preferred name for each.

Unfortunately, the current locale setting is global (not sure how global, though… any mod_perl experts want to comment?), so we’ll store it in a temporary variable during our calculations. I am worried, though, that if it’s too global, this code might not be thread-safe. Got to research that further.

Therefore, to store the old one, you can do:

use locale; use POSIX qw(locale_h); $oldlocale = setlocale(LC_NUMERIC); setlocale(LC_NUMERIC, <locale setting>); $separator = <locale separator> $decimal = <locale decimal point> # Should output with the correct decimal point for your locale. # Requires a quick rewrite to the commify() function in Perl cookbook code above to allow passing in desired separator and decimal. # You might also want to modify it to allow different number of decimals between separators. commify(sprintf(“%0.2f”, $floating_point_number), $separator, $decimal); setlocale(LC_NUMERIC, $oldlocale);

In mason, you can stick most of the code in the <%init> block, whereas the line that sets the locale back to the old locale can be stuck in the <%cleanup%gt; block.

That should do it!

Uncategorized

  1. No comments yet.
  1. No trackbacks yet.