树枝:如何围捕?

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.

Update

On versions 1.15.0+, round filter is available.

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

http://twig.sensiolabs.org/doc/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

Have you tried 7 // 2?

This documentation page might be useful.

http://php.net/manual/en/function.ceil.php

use the ceiling function of the php to do what you want

No idea how it is in previous versions, but in Symfony 2.2.1 you have to use parenthesis around your calculation (assuming you created the extension):

(7 / 2)|ceil

Apparently 7 / 2|ceil is the same as 7 / (2|ceil) since they both gave the same (wrong) result and only the above solution worked for me.

If you're using version 1.12.0 or newer, you can use the ternary operator and do something like this:

{{ ((7 / 2) > (7 // 2)) ? (7 // 2) + 1 : (7 // 2) }}

It's not so "elegant" but it works anyway.

http://twig.sensiolabs.org/doc/filters/round.html

Starting with Twig 1.15.0 you can use the 'round' filter and pass 'ceil' as the second parameter. The solution would look like this:

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

Formatting numbers for display definitely belongs to the view, not the controller. This would be considered display logic - which is different from the business logic in the controllers that should be kept as clean an minimal as possible.

New in version 1.15.0: The round filter was added in Twig 1.15.0.

Example: {{ 42.55|round(1, 'ceil') }}

The round filter takes two optional arguments; the first one specifies the precision (default is 0) and the second the rounding method (default is common)

http://twig.sensiolabs.org/doc/filters/round.html

The round filter takes the first argument as the precision. So the correct formulation to answer the OP's question would be:

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

rather than

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

http://twig.sensiolabs.org/doc/filters/round.html