Using PHP’s NumberFormatter to format currencies – Rob Allen's DevNotes


: 3

I've been using number_format() for a very long time, but recently discovered that within the intl extension there's a NumberFormatter class available too. This is quite a clever class as it is Locale aware and handles formatting currency, including the correct symbol.

You can check if you have the intl extension installed using php -m | grep intl and if you don't then you can install it with apt-get install php5-intl or yum install php-intl assuming you use your distro's stock PHP. (If you compile your own, then --enable-intl is the switch you need.)

Consider this scenario where I want to display a price in Euros for both the UK and the German markets:

The constructor takes the locale to use along with the type of formatting you want to do, CURRENCY in this case. Then, when you call formatCurrency(), the second parameter is the 3-letter alphabetic ISO 4217 code for the currency you want to display.

The output of the code above is:

You can see the locale at work here as in the UK we expect to see the currency symbol before the number and use comma to separate thousands, whereas in Germany, the currency symbol is (usually!) at the end of the number and the decimal point is used to separate the thousands.

The ISO 4217 currency code determines which currency symbol is returned. Obviously, for EUR, we get the € symbol. For GBP, we'd get £, etc.

Finally, if you use ZF2, this is all wrapped up into the currencyFormat view helper for you.