Search code examples
phptwigicutwig-filter

Documentation for Twig 3.x format_currency filter options?


I'm trying to output localized currency in a twig 3.x template. I have installed the "Intl" extension. Setting the currency and number of fractional digits is straightforward but the output doesn't include a thousands separator. I can't find a shred of documentation anywhere for any of the options some of which have incomprehensible names like "grouping_used". Is there somewhere I can look, or have I made a mistake in the html?

Twig:

{{ reservation.balance_due|format_currency('USD',{fraction_digit: 0}) }}

Output: $ 1234


Solution

  • The twig extension directly maps those attributes to intl NumberFormatter attributes. However, the NumberFormatter attributes are also pretty scarcely documented.

    "grouping_used" maps to NumberFormatter::GROUPING_USED. NumberFormatter::GROUPING_USED is in turn mapped to the UNUM_GROUPING_USED constant, which is from the ICU library. The documentation for the ICU library attributes can be found here.

    Unfortunately, it seems like the PHP documentation was largely copied from the ICU documentation.

    As to your concrete issue, it seems like the grouping_used attribute is indeed what you are looking for:

    {{ '1234'|format_currency('USD', {fraction_digit: 0, 'grouping_used': 1})}}
    {# Prints: $ 1,234 #}
    

    Note that format_currency is also affected by the current locale.

    {{ '1234'|format_currency('USD', {fraction_digit: 0}, locale='en_US') }}
    {# Also prints: $ 1,234 #}