Skip to content

round

The round filter rounds a numeric value to a specified number of decimal places (or to the nearest integer if no decimal places are specified).

Functionality

  • Numbers: Takes a numerical value as input (integer or floating-point).
  • Decimal Places (Optional): Accepts an optional integer argument specifying the number of decimal places to round to. If not provided, the number is rounded to the nearest integer.
  • Rounding: Rounds the input number to the specified number of decimal places using standard rounding rules (round half up).
  • Output: Returns a new numerical value representing the rounded result.

Syntax

    {{ input_number | round }} 
or

    {{ input_number | round: decimal_places }}
Arguments

  • decimal_places (optional): An integer indicating the number of decimal places to round to. Defaults to 0 (round to nearest integer) if not provided.

Code Samples

Example 1: Rounding to the Nearest Integer

    {% assign pi = 3.14159 %}

    {{ pi | round }}
Output:
3
Example 2: Rounding to Two Decimal Places

    {% assign price = 12.999 %}

    {{ price | round: 2 }}
Output:
13.00
Example 3: Rounding a Negative Number

    {% assign temperature = -17.35 %}
    {{ temperature | round: 1 }}

Output:

-17.4

Outliers and Special Cases

  • Non-Numeric Input: If the input is not a number (e.g., a string or boolean), the round filter might attempt to convert it to a number before rounding. If the conversion fails, an error might be thrown.
  • Large Decimal Places: Be cautious when rounding to a very large number of decimal places, as it can lead to potential floating-point precision issues.

Key Points

  • The round filter is essential for formatting and displaying numbers in a user-friendly way.
  • It is particularly useful when dealing with prices, calculations, or any scenario where precise decimal representation is not required.
  • You can control the level of precision by specifying the number of decimal places.
  • Be aware of the standard rounding rules (round half up) used by the filter.
  • Consider using the ceil or floor filters if you need to round up or down to the nearest integer, respectively.