Formatting money in twig templates

If you are using an older version of twig and you don't want to install any extensions you can use the format filter like this:

{{ "%.2f"|format(total) }}

Not very nice, but it works.

Basically format works like PHP's sprintf function


The number_format filter has been included in the Twig core since the end of December 2011. The relevant commit is here.

Usage: number_format(decimals, decimalSeparator, thousandSeparator)

{{ total|number_format(2) }}
{{ total|number_format(0, '.') }}
{{ total|number_format(2, '.', ',') }}

Read more about it in the docs


The Twig Extensions library contains a number of useful extensions for Twig. With the release of version 1.2.0, a localizedcurrency filter has been added to the Intl extension. As the name suggests, this filter will format a number based on the current locale. It uses PHP's NumberFormatter class to do so.

Usage

This filter is very easy to use. The only required argument for the filter is the 3-letter ISO 4217 currency code. For instance, to display an amount of 27.99 in Euros, use the following line of code:

{{ price|localizedcurrency('EUR') }}

This will display different results depending on the locale:

  • €27.99 if the locale is set to en
  • 27,99 € if the locale is set to fr
  • € 27,99 if the locale is set to nl

Installation / setting the locale

Installation instructions for the Intl extension can be found in this seperate answer.


Use the format_currency

From version 2.12 format_currency filter was added. More information in the official documentation https://twig.symfony.com/doc/2.x/filters/format_currency.html