Standard Library

PHP intl Functions

PHP Internationalization

PHP intl functions format numbers with NumberFormatter.

Introduction to PHP intl Functions

The PHP Internationalization Functions (intl) provide a suite of functions that help developers format numbers, dates, and other strings based on locale settings. One of the key components of the intl extension is the NumberFormatter class, which is used to format numbers according to specific cultural rules.

Setting Up the intl Extension

Before you can use the intl functions, you need to ensure that the intl extension is enabled in your PHP environment. You can do this by checking your php.ini file and looking for the line extension=intl. If it is commented out, uncomment it and restart your server.

Using NumberFormatter to Format Numbers

The NumberFormatter class is highly versatile and supports different styles of number formatting, including decimal, currency, percent, and more. Here's a basic example of how to use it to format numbers.

In this example, we create a NumberFormatter instance with the locale en_US and the style NumberFormatter::DECIMAL. The format method is then used to format the number according to U.S. conventions.

Formatting Currency Values

You can also use the NumberFormatter class to format currency values. This allows you to present numbers in a manner that is appropriate for financial transactions.

In this currency formatting example, the NumberFormatter class is initialized with NumberFormatter::CURRENCY to format numbers as currency. The output is formatted as U.S. dollars.

Handling Different Locales

One of the strengths of the NumberFormatter class is its ability to handle different locales, which is essential for creating international applications. Here's how you can format a number for a different locale, such as French (France):

In this example, we switch the locale to fr_FR, which formats the number according to French conventions, using a space as a thousand separator and a comma as a decimal separator.

Conclusion

The PHP intl functions, particularly the NumberFormatter class, provide powerful tools for number formatting in a way that is culturally appropriate. By leveraging these functions, developers can create applications that cater to a global audience with ease.