Nikolai Prokoschenko
Nikolai Prokoschenko

Reputation: 8765

How do I format number locale-specific in Perl?

I need to format numbers in my web application depending on user's chosen language, e.g. 1234.56 = "1.234,56" in German. Stuff like sprintf is currently out of question, since they depend on LC_NUMERIC (which is sensible for desktop applications IMHO) and I'd have to generate every locale on the server, which is a no-go. I would prefer using CLDR's formatting strings, but haven't found an appropriate module. What I'd like to have is a nutshell:

set_locale("de_DE");
print format_number(1234.56);

How does one do that properly?

Upvotes: 5

Views: 1673

Answers (3)

Nova Patch
Nova Patch

Reputation: 101

The CPAN now has CLDR::Number for Unicode CLDR-based number, percent, and currency formatting.

use CLDR::Number;
my $cldr = CLDR::Number->new(locale => 'de-DE');  # or 'de_DE'

my $decf = $cldr->decimal_formatter;
say $decf->format(1234.5);  # '1.234,5'

my $curf = $cldr->currency_formatter(currency_code => 'EUR');
say $curf->format(1234.5);  # '1.234,50 €'

$curf->locale('de-AT');     # Austrian German
say $curf->format(1234.5);  # '€ 1.234,50'

CLDR::Number provides all the locale data that it uses, currently from the CDLR v27, so you don't have to rely on inconsistent operating system locale data.

Upvotes: 6

castaway
castaway

Reputation: 572

use POSIX qw( locale_h );
use Math::Currency;
set_locale(LC_ALL, "de_DE");
Math::Currency->localize();
my $eur = Math::Currency->new("1234.56");

print "$eur";

That does, however, depend on the locales existing. Look at Math::Currency's docs for how to generate Math::Currency::XX submodules for all the data you need first, then install those on the server.. no locales needed then.

I also have a patched one somewhere that copes with various sorts of EUR. (Now if only the author would apply it ;)

Jess.

Upvotes: 4

Anonymous
Anonymous

Reputation: 50369

perldoc perllocale states:

The setlocale function You can switch locales as often as you wish at run time with the POSIX::setlocale() function:

It also notes the module I18N::Langinfo, which provides localization data piece by piece.

Upvotes: 1

Related Questions