I'm working with strings in Liquid and I want to convert them to numbers! Do you ever have such a situation? Just the other day, while writing a process in Liquid, I acquired information as a string (String), but wanted to convert it to a number (Integer) for addition or subtraction. I would like to convert it to a numerical value (Integer) and add or subtract it.

Necessity of converting String to Numeric

For example, when you want to add the string "1" and the number 1, the number may be unintentionally converted to a string, resulting in "11".

  • What you want to do
    1 (number) + 1 (number) = 2 (number)

  • Things that could become unintentional.

    "1" (string) + 1 (number) = "
    11" (string) "1" (string) + "1" (string) = "11" (string)

Different types, such as "1" and "2," may result in unintentionally different results. To avoid this, the calculation must first be made according to the numerical value.

How to Convert a String to a Numeric Value

Now, let's look at how to convert a string to a numerical value.

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


{% assign variable2 = variable2 | times: 1 %}

In this way, a value can be converted to a number by adding a plus or a multiplier to the value in advance.

The first plus 0 simply adds 0, so the value does not change, and the second times 1 also multiplies by 1, so the value does not change.

If you then do a plus or multiply, you should get a decent calculation result.

How to convert a Liquid string String to a numeric Integer in Shopify Summary

This was a short article on how to convert strings to numbers. Surprisingly, I could only find the information in English source, so please refer to it.

I think I use this conversion quite often when I am developing Shopify. I've looked into it several times in the last month or so! I hope this article was of some help to you.

Thank you for reading to the end. Have a great day!

Contact form