I’m struggling with basic data type conversions in Shopify’s Liquid. I tried a method I found online to change a string to a number. It suggested adding 0 to the variable like this:
{% assign new_number = old_string | plus:0 %}
But it’s not working for me. Is there a better way to do this in Liquid?
I’ve looked through the Liquid docs but can’t find a clear answer. Am I missing something obvious? It seems like such a common task. Any help would be great. I’m new to Liquid and feeling a bit lost with these simple operations.
hey there! i’ve had similar issues. the plus:0 trick can be finicky. have u tried the ‘to_number’ filter? like this:
{% assign new_number = old_string | to_number %}
it’s been more reliable for me. hope that helps! lemme know if u need more info.
I’ve encountered this exact issue in my Shopify development work. The ‘to_number’ filter suggested earlier is indeed a good option, but it’s worth noting that it’s not always foolproof. In my experience, a more robust approach is to use the ‘times’ filter with 1:
{% assign new_number = old_string | times: 1 %}
This method has consistently worked for me across various Shopify projects. It effectively coerces the string to a number by multiplying it by 1. It’s simple, reliable, and handles edge cases well. Just remember, Liquid’s type conversion can sometimes be tricky, so always test thoroughly with different input types.