Reputation: 529
I want to drop the decimal digits that are meaningless, like this:
14.50 => 14.5
14.0500 => 14.05
14.000 => 14
I was searching about how to do that, and I found the following way:
{{ number|trim('0')|trim('.') }}
But the only problem with the above filter is the following case:
0.023 => 023
Does anyone know how can I achieve this?
Upvotes: 2
Views: 2946
Reputation: 18751
You don't mention it anywhere, but I assume your "number" variables are actually strings, otherwise the default behaviour would be actually what you're expecting...
My suggestion is simply to cast those string
variables into float
variables somewhere in your PHP code, and Twig will render them as you'd expect.
That said, if you really need to do that in Twig, you can automatically cast your strings to numbers by performing any arithmetic operations on them. See the following example:
{% set stringNumber = '14.0500' %}
{% set number = 14.0500 %}
{{ stringNumber }} {# Prints 14.0500 #}
{{ number }} {# Prints 14.05 #}
{{ stringNumber + 0 }} {# Prints 14.05 #}
Full example here: https://twigfiddle.com/hwl82b
Upvotes: 5