Twig: How to round up?
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
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
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.
Have you tried 7 // 2
?
This documentation page might be useful.