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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With