Skip to content

format_discount_percentage

The format_discount_percentage macro turns a number into a readable discount label. It follows these rules: - Adds a minus sign (-) for discounts. - Adds a plus sign (+) for extra charges. - Shows no sign for exactly zero. - Keeps one decimal place for numbers between -1 and 1 (like 0.5). - Rounds all other numbers to a whole number.

Definition

{% macro format_discount_percentage(percentage) %}

Input parameters

percentage

number A raw percentage value representing the discount or surcharge. Positive values are treated as discounts (rendered with -), negative values as surcharges (rendered with +).

Output

string A formatted percentage string, for example -15%, +0,5% or 0%.

Formatting rules

Input range Example input Output
0 (after rounding to 1 decimal) 0.04 0%
(-1, 0) ∪ (0, 1) 0.7 -0,7%
≥ 1 (discount) 15.6 -16%
≤ -1 (surcharge) -3.2 +3%

Example

Basic usage — render a formatted discount badge next to a regular price.

{% from "@macros/format_discount_percentage.twig" import format_discount_percentage %}
{% from "@macros/price_base.twig" import price_base %}

{{ price_base(format_discount_percentage(product.specialOffer.discountPercentage), '', {
    price: 'price_s',
    priceValue: 'price__value_special'
}) }}

Example

Usage with a computed percentage (e.g. lowest historical price comparison).

{% from "@macros/format_discount_percentage.twig" import format_discount_percentage %}
{% from "@macros/price_base.twig" import price_base %}

{% set lowestPricePercentage = 100 - (product.price.grossValue * 100 / product.lowestHistoricalPriceInLast30Days.getPrice().grossValue) %}

{{ price_base(format_discount_percentage(lowestPricePercentage), '', {
    price: 'price_xs',
    priceValue: 'price__value_special'
}) }}

Macro source code

{% macro format_discount_percentage(percentage) -%}
    {%- set absRounded = percentage|round(1)|abs -%}
    {%- if absRounded == 0 -%}
        0%
    {%- else -%}
        {%- set sign = percentage > 0 ? '-' : '+' -%}
        {%- if absRounded < 1 -%}
            {{- sign ~ absRounded|number_format(1, ',', '') ~ '%' -}}
        {%- else -%}
            {{- sign ~ (percentage|abs|round(0)|number_format(0, ',', '')) ~ '%' -}}
        {%- endif -%}
    {%- endif -%}
{% endmacro %}

Macros reference