Formatting money in twig templates

NumbersFormatCurrencyTwig

Numbers Problem Overview


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

Numbers Solutions


Solution 1 - Numbers

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 - Numbers

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 - Numbers

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

Solution 4 - Numbers

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionumpirskyView Question on Stackoverflow
Solution 1 - NumbersJrgnsView Answer on Stackoverflow
Solution 2 - NumbersNic WortelView Answer on Stackoverflow
Solution 3 - NumbersJensView Answer on Stackoverflow
Solution 4 - NumbersPanagiotis KoursarisView Answer on Stackoverflow