Categories
PHP

PHP formatCurrency alternative

In PHP we have a nice class to handle numbers with the extension NumberFormatter, unluckily all the shared hostings I have tried do not include such library.

I had to format a price for a product that could use different currencies… In symfony, zend and yii just to mention some have alternatives to this library.

In my case I only needed the formatCurrency without all the mess around the huge modules.

I had implemented this in Open eShop in the i18n class (commit) but here I want to share the procedural function and specially the currencies conversion, which took me a lot of time to verify.

Examples how to use:

 echo '
'.formatcurrency(39174.00000000001); echo '
'.formatcurrency(1000045.25, "CHF"); echo '
'.formatcurrency(1000045.25, "EUR"); echo '
'.formatcurrency(1000045, "JPY"); echo '
'.formatcurrency(1000045, "VND"); echo '
'.formatcurrency(1000045.25, "INR"); echo '
'.formatcurrency(1000045.25, "ILS"); echo '
'.formatcurrency(1000045.25, "THB"); echo '
'.formatcurrency(1000045.25, "KRW");

Source code.