Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``number_format`` |
| 2 | ================= |
| 3 | |
| 4 | The ``number_format`` filter formats numbers. It is a wrapper around PHP's |
| 5 | `number_format`_ function: |
| 6 | |
| 7 | .. code-block:: twig |
| 8 | |
| 9 | {{ 200.35|number_format }} |
| 10 | |
| 11 | You can control the number of decimal places, decimal point, and thousands |
| 12 | separator using the additional arguments: |
| 13 | |
| 14 | .. code-block:: twig |
| 15 | |
| 16 | {{ 9800.333|number_format(2, '.', ',') }} |
| 17 | |
| 18 | To format negative numbers or math calculation, wrap the previous statement |
| 19 | with parentheses (needed because of Twig's :ref:`precedence of operators |
| 20 | <twig-expressions>`): |
| 21 | |
| 22 | .. code-block:: twig |
| 23 | |
| 24 | {{ -9800.333|number_format(2, '.', ',') }} {# outputs : -9 #} |
| 25 | {{ (-9800.333)|number_format(2, '.', ',') }} {# outputs : -9,800.33 #} |
| 26 | {{ 1 + 0.2|number_format(2) }} {# outputs : 1.2 #} |
| 27 | {{ (1 + 0.2)|number_format(2) }} {# outputs : 1.20 #} |
| 28 | |
| 29 | If no formatting options are provided then Twig will use the default formatting |
| 30 | options of: |
| 31 | |
| 32 | * 0 decimal places. |
| 33 | * ``.`` as the decimal point. |
| 34 | * ``,`` as the thousands separator. |
| 35 | |
| 36 | These defaults can be changed through the core extension:: |
| 37 | |
| 38 | $twig = new \Twig\Environment($loader); |
| 39 | $twig->getExtension(\Twig\Extension\CoreExtension::class)->setNumberFormat(3, '.', ','); |
| 40 | |
| 41 | The defaults set for ``number_format`` can be over-ridden upon each call using the |
| 42 | additional parameters. |
| 43 | |
| 44 | Arguments |
| 45 | --------- |
| 46 | |
| 47 | * ``decimal``: The number of decimal points to display |
| 48 | * ``decimal_point``: The character(s) to use for the decimal point |
| 49 | * ``thousand_sep``: The character(s) to use for the thousands separator |
| 50 | |
| 51 | .. _`number_format`: https://secure.php.net/number_format |