In AnQiCMS template development, data processing is one of the core links.The flexible content model allows us to customize various fields to store website information, including scenarios where numbers are needed, such as product prices, inventory quantities, ratings, etc.Although these numbers may look normal in the background, they are likely to be presented as strings when called in the template.This brings up a common question: How to convert these numeric strings into floating-point numbers or integers in the template, so that mathematical operations or specific formatting can be performed?

AnQiCMS is a powerful template engine that draws inspiration from Django syntax, providing a rich set of filters (Filters) to handle such needs.Understand and make good use of these filters, which can make your template development more efficient and accurate.

Why do you need to convert a numeric string to a floating-point number or integer?

Imagine, you have set a "Original Price" field in the background, entered "199.99", and another "Discount Rate" field entered "0.8".{{ product.OriginalPrice * product.DiscountRate }}It often turns out that the calculation results are incorrect, even causing page rendering errors.This is because the template engine recognizes "199.99" and "0.8" as plain text, not as values that can be calculated.

To solve this problem, we need to explicitly convert these strings to numeric types in the mathematical sense. AnQiCMS providesintegerandfloatTwo very practical filters, specifically designed for handling this type of conversion.

UseintegerFilter that converts a numeric string to an integer.

If you are sure a value is an integer or you only care about its integer part (for example, when calculating inventory quantities, product quantities), thenintegerThe filter is your helpful assistant.

The function attempts to convert the input numeric string to an integer. The usage is very intuitive, just append a pipe symbol to the variable|AddintegerJust do it.

For example, if you have a variableitem.CountThe value is a string “150”, you can convert it to an integer like this:

<p>库存数量:{{ item.Count | integer }}</p>

After the conversion, you can perform operations such as addition, subtraction, multiplication, and division on{{ item.Count | integer }}The result. It is worth noting that ifitem.CountThe value is a floating-point number (such as “150.75”),integerThe filter will truncate the decimal part directly, retaining only the integer 150. If an attempt is made to convert a non-numeric string (such as “hello”) to an integer,integerThe filter will return the default value0.

UsefloatThe filter will convert the number string to a floating point number

When you are processing prices, ratios, percentages, and other data that may contain decimals,floatthe filter becomes indispensable.

floatThe function of the filter is to try to convert a numeric string into a floating-point number. Its usage is similar tointegerThe filter is similar to:

<p>商品价格:¥ {{ item.Price | float }}</p>

Ifitem.PriceThe value is the string "99.99", afterfloatAfter the filter, it will become a true floating-point number99.99Thus, you can confidently perform precise decimal-place mathematical operations. For example, calculating taxes or discount prices.integerThe filter is similar, if the value passed in is a non-numeric string,floatThe filter will return the default value0.0.

Combined with actual application scenarios

Let us illustrate the actual application of these two filters with a more specific example. Suppose you have a product detail page that contains a custom field named "Original Price (original_price)” and “discount rate (“discount_rate)”, they are both stored as strings. Now, you want to calculate and display the discounted price, ensuring that the price is displayed with two decimal places.

{# 假设这是在产品详情页面的某个区块 #}
{% archiveDetail productDetailData %}
    {% if productDetailData %}
        {# 假设 original_price 和 discount_rate 是通过自定义字段获取 #}
        {# 在实际使用中,您可以直接访问 productDetailData.original_price 或 productDetailData.discount_rate #}
        {# 这里为了演示,我们假设它们来自一个params对象 #}
        {% archiveParams productCustomFields with id=productDetailData.Id %}
            {% set originalPriceStr = productCustomFields.original_price.Value %}
            {% set discountRateStr = productCustomFields.discount_rate.Value %}

            {# 将字符串转换为浮点数 #}
            {% set originalPrice = originalPriceStr | float %}
            {% set discountRate = discountRateStr | float %}

            {# 进行数学计算 #}
            {% set finalPrice = originalPrice * (1 - discountRate) %}

            <div class="product-price-info">
                <p>原价:<span class="original-price">¥ {{ originalPrice | floatformat:2 }}</span></p>
                <p>折扣:<span class="discount-rate">{{ discountRate * 100 | integer }}%</span></p> {# 将折扣率转换为百分比整数显示 #}
                <p>折后价:<span class="final-price">¥ {{ finalPrice | floatformat:2 }}</span></p> {# 使用 floatformat 过滤器格式化为两位小数 #}
            </div>
        {% endarchiveParams %}
    {% endif %}
{% endarchiveDetail %}

In this example, we first go throughfloatThe filter willoriginalPriceStranddiscountRateStrConvert to a computable floating point number. Then, simple subtraction and multiplication operations were performed. When displaying the discount rate, we willdiscountRateMultiply by 100 and then useintegerRound off the filter, show as a percentage. Finally, to make the price display more standardized, we usefloatformat:2A filter to ensurefinalPriceAlways displayed to two decimal places. This demonstrates how the filters work together to provide precise and beautiful data display.

Cautionary notes and **practice

  • Data source: Usually, string data that needs to be converted to numbers comes from the backend custom fields.When defining these fields, although any text may be allowed, it is best to perform type conversion in template processing if the expected use is numerical.
  • chaining call: AnQiCMS's filter supports chained calls. For example,{{ "5.6" | float | integer }}It will first convert '5.6' to the floating point number 5.6, and then convert it to the integer 5.
  • Default valueWhen conversion fails (for example, converting “abc” to a number),integerthe filter will return0,floatthe filter will return0.0In some cases, you may need to set more friendly default displays for these unexpected situations, you can usedefaultFilter to process, for example{{ item.Count | integer | default:"N/A" }}.
  • Display accuracy: For floating-point numbers, especially when involving currency or precise measurement, usefloatformatThe filter to control the number of decimal places is **practical. It not only ensures consistency in display but also handles rounding.
  • Only when displayedIf the numeric string is only used for display and does not involve any calculation or specific format requirements, it is usually not necessary to perform type conversion.The template engine automatically handles the rendering of most basic types when displayed.

Frequently Asked Questions (FAQ)

1. Why does my numeric field display directly in the template, but it throws an error when performing calculations or comparisons?

This is because in the AnQiCMS template, data obtained from custom fields (even if the content is numeric) is default may be treated as a string type.Although the template engine can directly display the string "123", it cannot perform mathematical operations on the string directly, such as "123" * 2.integerorfloatThe filter converts it to an actual numeric type for calculations.

2.integerandfloatWhat are the main differences between filters? When should I choose to use them?

integerFilters convert a numeric string to an integer. If the original value contains a decimal,integerThe decimal part is truncated directly (for example, “3.7” becomes 3). It is suitable for scenarios where decimals are not needed, such as quantities, IDs, etc.

floatThe filter converts a numeric string to a floating-point number.It will retain the decimal part (for example, "3.7" is converted to 3.7).It is suitable for scenarios that require accuracy to decimal places, such as prices, percentages, and measurement values.

Choose which one depends on your data characteristics and calculation needs. If the data may contain decimals, please make sure to usefloat.

3. If my custom field content is not purely numeric, such as 'about 100 yuan', useintegerorfloatWhat will happen to the filter?

When trying to convert non-numeric string to number,integerthe filter will return0whilefloatthe filter will return0.0.This is an error handling mechanism of the AnQiCMS template engine.ifDoes the converted value check0or0.0Therefore, to determine if the conversion is successful.