Search code examples
formszend-framework2locale

ZendFramework 2: Locale Currency values in a form


Is there any way to convert how a text input displays a currency in its value in correct locale number format from within the Form construct method or ViewHelper?

e.g.

  1. value from database is 10000.50
  2. In US or UK, is viewed as 10,000.50
  3. In EUR is viewed as 10.000,50

I have been able to do the conversions in controllers, models and views, but haven't come across how do do it here.

Thanks

Aborgrove


Solution

  • You have the Zend\I18n component which ships formatters to format numbers. You can both use the NumberFormat for numbers in general and the CurrencyFormat for specifically currencies.

    These formatters are living in the Zend\I18n\View\Helper domain, but are not dependant on the view actually. Therefore, you can just use them anywhere you want:

    use Zend\I18n\View\Helper\CurrencyFormat;
    
    $formatter = new CurrencyFormat;
    $formatter->setLocale('en-US');
    
    $currency  = $formatter(1234.56, 'EUR'); // "€1,234.56"
    $currency  = $formatter(1234.56, 'USD'); // "$1,234.56"
    
    $formatter->setLocale('nl-NL');
    $currency  = $formatter(1234.56, 'EUR'); // "€ 1.234,56"
    

    You have to be aware of two things:

    1. The number formatting style is depending on the locale, so supply the correct locale (or set the default locale with Locale::setDefault()).
    2. The "EUR" or "USD" is only for the signs, and together with the locale will be prepended or appended to the number formatted

    You can simply use the Zend\I18n\View\Helper\NumberFormat if you only want to format the numbers without any currency code. More information about the formatting is available in the manual.