Skip to content

divided_by

The divided_by filter performs division of a number by another number. It handles both integer and floating-point division, adjusting the output type based on the divisor.

Functionality

  • Numbers: Takes a numerical value (integer or floating-point) as the dividend (the number being divided).
  • Divisor: Requires a numerical argument as the divisor (the number to divide by).
  • Division: Performs division of the dividend by the divisor.
  • Output: Returns a numerical value representing the result of the division:
    • If the divisor is an integer, the result is an integer (rounded down).
    • If the divisor is a floating-point number, the result is a floating-point number.

Syntax

    {{ input_number | divided_by: divisor }}

Arguments

  • divisor: The number to divide the input number by.

Code Samples

Example 1: Integer Division

    {% assign total_items = 10 %}
    {% assign groups = 3 %}
    {{ total_items | divided_by: groups }}

Output:

3
Example 2: Floating-Point Division

    {% assign price = 15.99 %}
    {% assign quantity = 2.5 %}
    {{ price | divided_by: quantity }}

Output:

6.396
Example 3: Division by Zero (Error)

    {% assign value = 10 %}
    {% assign zero = 0 %}
    {{ value | divided_by: zero }}  

Output: (Throws an error)

Liquid error: divided by 0

Outliers and Special Cases

  • Division by Zero: Attempting to divide by zero will result in an error.
  • Non-Numeric Input: If the input or the divisor is not a number (e.g., a string), the filter might attempt to convert it to a number. If the conversion fails, an error might be thrown.
  • Data Type of Result: The result's data type (integer or float) depends on the data type of the divisor.
  • Rounding: When performing integer division, the result is rounded down to the nearest integer.

Key Points

  • The divided_by filter is essential for performing basic arithmetic calculations within your templates.
  • It is particularly useful when calculating averages, ratios, or distributing quantities.
  • Be aware of the potential for division by zero errors and ensure that both the input and the divisor are valid numerical values.
  • Understand the rounding behavior of the filter when working with integer division.