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!

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:

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

Formatting Styles

Formatting styles describe how our numbers should be formatted: decimal, currency, duration, etc. Check the list of available formatting styles in the documentation. Let’s try some examples for different styles:

We can use the attributes we mentioned earlier ($numberFormatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);) with currencies, too.

Timezones

Before using PHP Intl calendars, we need to brush up on timezones and try a quick example:

A time zone is a region that observes a uniform standard time for legal, commercial, and social purposes. Time zones tend to follow the boundaries of countries and their subdivisions because it is convenient for areas in close commercial or other communication to keep the same time.

— Wikipedia

The IntlTimeZone class is responsible for creating and managing timezones. This is no different from timezones in the DateTimeZone class:

Conclusion

In this two part series, we discovered the PHP Intl extension and the ICU library. The extension still has some other parts like Collators, Spoofchecker, UConverter, etc. We’ll focus on those in subsequent posts, but in the meanwhile, if you have any questions or comments, please leave them below!

Younes is a freelance web developer, technical writer and a blogger from Morocco. He's worked with JAVA, J2EE, JavaScript, etc., but his language of choice is PHP. You can learn more about him on his website.