Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 446
Nikolai Prokoschenko Avatar asked Dec 31 '22 01:12

Nikolai Prokoschenko


1 Answers

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.

like image 195
Nova Patch Avatar answered Jan 08 '23 23:01

Nova Patch