Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding numbers in Twig

Tags:

php

twig

symfony

Does someone know how to round down numbers in Twig to the nearest whole number?

Ex : 2.6 => 2

I tried to use |number_format but it doesn't round down them.

like image 218
Xuan-Thi Nguyen Avatar asked May 21 '12 08:05

Xuan-Thi Nguyen


3 Answers

@olivierw's answer is correct, but there's another trick you can use. Twig does have // operator which floors down result of division. You can use it as {{ variable // 1 }} which equals to intval(floor(variable)).

like image 78
Ondrej Slinták Avatar answered Nov 01 '22 17:11

Ondrej Slinták


Follow the instructions on this page to create your own filter:

$twig = new Twig_Environment($loader);
$twig->addFilter('floor', new Twig_Filter_Function('floor'));

Then in your template:

{{ myNumber|floor }}
like image 44
Visavì Avatar answered Nov 01 '22 17:11

Visavì


Since twig 1.15, you can use round filter.

{{ 2.6|round(0, 'floor') }}

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

like image 43
pastorello Avatar answered Nov 01 '22 18:11

pastorello