File: number_format.rst

package info (click to toggle)
php-twig 3.21.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 6,220 kB
  • sloc: php: 24,694; makefile: 110; sh: 43
file content (57 lines) | stat: -rw-r--r-- 1,797 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
``number_format``
=================

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

.. code-block:: twig

    {{ 200.35|number_format }}

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

.. code-block:: twig

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

To format negative numbers, wrap the previous statement with parentheses (note
that as of Twig 3.21, not using parentheses is deprecated as the filter
operator will change precedence in Twig 4.0):

.. code-block:: twig

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

To format math calculation, wrap the previous statement with parentheses
(needed because of Twig's :ref:`precedence of operators -<twig-expressions>`):

.. code-block:: twig

    {{ 1 + 0.2|number_format(2) }} {# outputs : 1.2 #}
    {{ (1 + 0.2)|number_format(2) }} {# outputs : 1.20 #}

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 changed through the core extension::

    $twig = new \Twig\Environment($loader);
    $twig->getExtension(\Twig\Extension\CoreExtension::class)->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

.. _`number_format`: https://www.php.net/number_format