Base Concepts of Internationalization in PHP : Page 3

Discover how to use internationalized numbers, currencies and dates/times with the I18N PEAR package.

by Octavia Andreea Anghel

Aug 7, 2008

Page 3 of 4

Using the I18N_Number Class
This class localizes numbers. It formats a given number using either a default or defined format. The format function has the following prototype:

string format(mixed $number, [mixed $format = null]): Returns the formatted $number according to the format specified by the $format argument, which takes one of the values: I18N_NUMBER_FLOAT, I18N_NUMBER_INTEGER or a custom format created using the setFormat method described next. If the $format argument is missing then the default value is I18N_NUMBER_FLOAT.

The class inherits its next two functions from the I18N_Format class:

int setFormat(string $format): Define a custom format given by the $format argument.

void getFormat(): Returns a format identifier that can be passed to the format method for specifying the number's format type.

The following example sets a custom format and returns the formatted number and the associated format identifier:

Listing 1 shows a longer example that formats a given number for different languages. The listing sets up a simple input page where users can enter a number. It then formats the number appropriately for a range of different language codes. Figure 1 shows a screenshot of the simple interface.

Figure 1. Simple Numeric-Entry Interface: When a user enters a numeric value and clicks Send, the application displays the entered value in a variety of locale-specific formats.

For example, if a user entered 123456, the program would produce results like these:

Using the I18N_Currency class
You use the I18N_Currency class to localize currency values and format specified amounts using a default or defined format. The format function has the next prototype:

void format(mixed $amount, [mixed $format = I18N_CURRENCY_LOCAL]): Returns the $amount formatted according to the specified format, which can be either I18N_CURRENCY_LOCAL, or I18N_CURRENCY_INTERNATIONAL, or can take a custom format created using the setFormat method described next. If the $format argument is missing, the default value is I18N_CURRENCY_LOCAL.

The I18N_Currency class inherits the setFormat and getFormat methods from the I18N_Format class (see the preceding section, "Using the I18N_Number Class").

Here's a short sample application that formats a given amount for different languages. This example uses a simple data-entry interface identical to the previous example (see Figure 1), and formats the user's entry appropriately for several different locales. You can download the complete code; the example below shows only the pertinent PHP code in the page: