Convert string to integer in Shopify Liquid?

42,972

Using assign with a math filter is correct. See this thread on GitHub, and this blog post.

Variables created through {% capture %} are strings. When using assign, either of these options should give you a number:

{% assign var1 = var1 | plus: 0 %}
{% assign var2 = var2 | times: 1 %}

If this doesn't work for you, can you post the relevant code?

Share:
42,972
MountainX
Author by

MountainX

You may be interested in the story of SE moderator Monica Cellio and how she was unfairly treated by the corporate management of this site. More info here. An update is available. Let's hope we can cultivate a more fair environment for content creators and moderators going forward.

Updated on July 09, 2022

Comments

  • MountainX
    MountainX almost 2 years

    I just read this related answer:

    How can I convert a number to a string? - Shopify Design — Ecommerce University

    To convert a string to a number just add 0 to the variable:

    {% assign variablename = variablename | plus:0 %}

    Not super elegant but it works!

    Inelegant or not, the answer given there isn't working for me. What's the right way to do this?

    Are the Liquid docs really missing such basic answers or am I just not finding the right place to look?

  • MountainX
    MountainX over 9 years
    I got it working. I'm just learning Liquid. Thanks for the two links. I read them both.