How to write float with Twig?
if((float)$a == (float)$b) {
echo true;
} else {
echo false;
}
Any ideas how to fix this?
Doing (float) $a
is basically the same as floatval($a)
(see Typecasting vs function to convert variable type in PHP).
Twig doesn't natively have a floatval
function, but you can add it yourself. Add this code to register a function or a filter. You can of course register both if you want. Add the code e.g. near where $twig
is defined.
$twig->addFunction(new \Twig_Function('floatval', 'floatval'));
$twig->addFilter(new \Twig_Filter('floatval', 'floatval'));
As the documentation says:
The first argument passed to the
Twig_Filter
constructor is the name of the filter you will use in templates and the second one is the PHP callable to associate with it....
Functions are defined in the exact same way as filters, but you need to create an instance of
Twig_Function
.
Then you can use the new function in Twig like this:
{% if floatval(a) == floatval(b) %}
{{ true }}
{% else %}
{{ false }}
{% endif %}
{# Shorter: #}
{{ floatval(a) == floatval(b) ? true : false }}
Or using the new filter:
{% if a|floatval == b|floatval %}
{{ true }}
{% else %}
{{ false }}
{% endif %}
{# Shorter: #}
{{ a|floatval == b|floatval ? true : false }}