Google Tag Manager

Forum Discussion

phil_l's avatar
phil_l
Supporter
6 hours ago

Liquid: Check if a variable is a number or string

Liquid's handling of strings/numbers is a little crazy. The standard/suggested approach of multiplying by 1 or adding 0 to a string to check if it's a number is broken if the first character of the string is a number. e.g.

{% assign my_string = '2 Fast 2 Furious' %}
{% assign my_string = my_string | plus:0 %}
{{my_string}}

Outputs "2".

{{'2 Fast 2 Furious'| times: 5}}

Outputs "10"

My workaround is split the string into parts and check if anything in it is not a number, which seems like a really inefficient way to do things. e.g.

{% assign my_string = '2PAC Shakur' %}
{% assign s = my_string | strip %}
{% assign digits = '0123456789' %}
{% assign is_digits_only = true %}

{% assign chars = s | split: '' %}
{% for c in chars %}
{% if digits contains c %}
{% else %}
{% assign is_digits_only = false %}
{% endif %}
{% endfor %}

{% if is_digits_only %}
Only numbers, but still not ideal if the variable starts with 0
{% else %}
Not numbers, unless it's a decimal. LOL. 
I need another loop or ceil/floor to check if decimal.
{% endif %}

Any chance of adding the equivalent of typeof to Liquid?

1 Reply

  • That's interesting- I've never had to check whether a variable is a string or a number, what's your use case? Do you get a lot of unchecked data in?