Skip to content

modulo

The modulo filter calculates the remainder after a division operation. It is also known as the "modulus" or "mod" operator.

Functionality

  • Numbers: Takes a numerical value as input (integer or floating-point).
  • Divisor: Requires a numerical argument specifying the divisor (the number to divide by).
  • Modulo Operation: Performs the modulo operation, which returns the remainder after dividing the input number by the divisor.
  • Output: Returns a new integer value representing the remainder.

Syntax

    {{ input_number | modulo: divisor }}
Arguments

  • divisor: The number to divide the input number by, and obtain the remainder. This argument is mandatory.

Code Samples

Example 1: Even/Odd Check

    {% assign number = 7 %}

    {% if number | modulo: 2 == 0 %}
      Number is even
    {% else %}
      Number is odd
    {% endif %}

Output:

Number is odd
Example 2: Cyclic Counting

    {% for i in (1..10) %}
      {{ i | modulo: 3 }} 
    {% endfor %}

Output:

1 2 0 1 2 0 1 2 0 1
Example 3: Invalid Usage (Missing Argument)

    {% assign value = 15 %}
    {{ value | modulo }} 
Output: (Throws an error)
Liquid error: The filter 'modulo' requires an argument.

Outliers and Special Cases

  • Missing Argument: The modulo filter requires the divisor argument. Failing to provide it will result in an error.
  • Division by Zero: Attempting to use a divisor of zero will lead to an error.
  • Non-Numeric Input: If the input or the divisor is not a number, the filter might attempt to convert it to a number. If the conversion fails, an error might be thrown.
  • Floating-Point Modulo: The modulo filter is primarily designed for integers. While it can work with floating-point numbers, the results might not always align perfectly with mathematical expectations due to floating-point representation limitations.

Key Points

  • The modulo filter is a valuable tool for tasks involving remainders, cyclic patterns, or determining divisibility.
  • It is commonly used in programming and mathematical contexts.
  • Be sure to provide a valid divisor argument.
  • Exercise caution when using floating-point numbers with the modulo operation.