Using PHP's NumberFormatter to format currencies

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.

3 thoughts on “Using PHP's NumberFormatter to format currencies

  1. This is very informative article I my self was searching this…. thanks for writing for us

  2. Do you know a way to print using a given locale (depends on the user) but always showing the currency sign (EUR in my case) at the end?

    This is useful because when you are printing, say, the price of a house, you want the default format of the given locale. But when you are printing a list of prices (e.g. an invoice or similar), you want them right-aligned, with the euro sign at the end.


Comments are closed.