[Special Summer Sale] 40% OFF All Magento 2 Themes

Cart

Convert string to integer in Shopify Liquid?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #9224
    David Hoang
    Keymaster

    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?

    #9222
    David Hoang
    Keymaster

    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?

    #9223
    David Hoang
    Keymaster

    In Shopify Liquid programming language, you can convert a string to an integer using the to_i filter.

    For example, if you have a variable string_number that contains a string representation of a number, you can convert it to an integer using the following code:

    {{ string_number | to_i }}
    

    It will convert the string to integer and you can use it in mathematical calculations, comparisons and other operations that work with integers.

    For example, you could use the to_i filter to add two numbers together:

    {% assign number_1 = "5" %}
    {% assign number_2 = "2" %}
    {% assign result = number_1 | to_i + number_2 | to_i %}
    {{ result }}
    

    This will output: 7

    Please note that this filter will return 0 if the string is not a valid number.

    Source

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.