Search code examples
phpsymfonytwignumber-formatting

Twig: How to round up?


I have a division in twig. Sometimes, the result can be with decimals and i need to have always a rounded up result.

Ex.

7 / 2 = 3.5

I would like to have

7 / 2 = 4

I know how to use floor in twig:

7 / 2 | floor = 3

But this is rounding to the down digit, not to the upper one.

I know also that i can use number_format

7 / 2 | number_format(0, '.', ',') = 3

So this will also take the down digit.

Any idea on how to tell twig to take the upper digit ?

This can be done in a controller (Symfony), but I am looking for the twig version.

Thank you.


Solution

  • Update

    On versions 1.15.0+, round filter is available.

    {{ (7 / 2)|round(1, 'ceil') }}
    

    https://twig.symfony.com/doc/3.x/filters/round.html


    You can extend twig and write your custom functions as it is described here

    And it will be something like this:

    <?php
    // src/Acme/DemoBundle/Twig/AcmeExtension.php
    namespace Acme\DemoBundle\Twig;
    
    class AcmeExtension extends \Twig_Extension
    {
        public function getFilters()
        {
            return array(
                'ceil' => new \Twig_Filter_Method($this, 'ceil'),
            );
        }
    
        public function ceil($number)
        {
            return ceil($number);
        }
    
        public function getName()
        {
            return 'acme_extension';
        }
    }
    

    So you can you use it in twig:

    (7 / 2) | ceil