a SensioLabs Product

The flexible, fast, and secure
template engine for PHP

You are reading the documentation for Twig 1.x. Switch to the documentation for Twig 2.x.

Table of Contents

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

number_format

New in version 1.5: The number_format filter was added in Twig 1.5

The number_format filter formats numbers. It is a wrapper around PHP's number_format function:

1
{{ 200.35|number_format }}

You can control the number of decimal places, decimal point, and thousands separator using the additional arguments:

1
{{ 9800.333|number_format(2, '.', ',') }}

To format negative numbers, wrap the number with parentheses (needed because of Twig's precedence of operators:

1
2
{{ -9800.333|number_format(2, '.', ',') }} {# outputs : -9 #}
{{ (-9800.333)|number_format(2, '.', ',') }} {# outputs : -9,800.33 #}

If no formatting options are provided then Twig will use the default formatting options of:

  • 0 decimal places.
  • . as the decimal point.
  • , as the thousands separator.

These defaults can be easily changed through the core extension:

1
2
3
4
5
$twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setNumberFormat(3, '.', ',');

// before Twig 1.26
$twig->getExtension('core')->setNumberFormat(3, '.', ',');

The defaults set for number_format can be over-ridden upon each call using the additional parameters.

Arguments

  • decimal: The number of decimal points to display
  • decimal_point: The character(s) to use for the decimal point
  • thousand_sep: The character(s) to use for the thousands separator
Website powered by Symfony and Twig, deployed on
The Twig logo is © 2010-2017 SensioLabs