Formatting money in twig templates

Are there any filters or something like that in twig template engine to format money or numbers?


Solution 1:

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

Solution 2:

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.

Solution 3:

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