Friday, May 20, 2016

Localizing Dates, Currency, and Numbers with Php-Intl

The first part of this series was an introduction of the PHP Intl extension and of how to localize your application's messages. In this part, we're going to learn about localizing numbers, dates, calendars, and similar complex data. Let's get started!

Globe stock illustration

Localizing Decimals

This may sound odd, but one of my main concerns when formatting numbers is working with decimal points, as they differ from place to place. Check Wikipedia for more details about different decimal mark variations.

Style
1,234,567.89
1234567.89
1234567,89
1,234,567·89
1.234.567,89
1˙234˙567,89
12,34,567.89
1'234'567.89
1'234'567,89
1.234.567'89
123,4567.89

The PHP Intl extension has a NumberFormatter which deals with number localization:

$numberFormatter = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
var_dump( $numberFormatter->format(123456789) );

$numberFormatter = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
var_dump( $numberFormatter->format(123456789) );

$numberFormatter = new NumberFormatter( 'ar', NumberFormatter::DECIMAL );
var_dump( $numberFormatter->format(123456789) );

$numberFormatter = new NumberFormatter( 'bn', NumberFormatter::DECIMAL );
var_dump( $numberFormatter->format(123456789) );

string(11) "123.456.789"
string(11) "123,456,789"
string(22) "١٢٣٬٤٥٦٬٧٨٩"
string(30) "১২,৩৪,৫৬,৭৮৯"

The first parameter is the locale code, and the second is the formatting style. In this case, we're formatting decimals.

Continue reading %Localizing Dates, Currency, and Numbers with Php-Intl%


by Younes Rafie via SitePoint

No comments:

Post a Comment