How do you check if a string in Jekyll is actually a number? For example you might want to do one thing when a value is '123' and another when the value is 'ABC'. Jekyll doesn’t seem to provide a simple way to do this out of the box. Crazy that such a simple feature doesn’t exist!

I’ve come up with a method. The logic is to treat the string as if it were a number and see how it reacts. A string of letters cannot be added to, but a string of numbers can. plusing a string that’s not a number will return 0, while plusing a string that’s a number will return the original number.

Method

  
    <!-- Get the value. -->
    {% assign value = '123' %}
    <!-- Add the value. -->
    {% assign addition = value | plus: 0 %}
    <!-- Convert addition to string for comparison. -->
    {% capture addition %}{{addition}}{% endcapture %}

    <!-- Value is a number if addition has no effect. -->
    {% if value == addition %}
      <!-- Value is number. -->
    {% endif %}
  

Let me know if there’s a better way to do this!

This method seems pretty robust. Only integers and floats without other characters in the string are considered numbers. The value '0' is correctly identified as a number.