When working with content display and logical judgment in the Anqi CMS template, we often encounter situations where we need to perform operations on numbers. However, even though the data obtained from the database or content model looks like numbers in the background, on the template level, they are sometimes presented as strings (stringThe form is passed in this way.At this point, if arithmetic operations or numerical comparisons are performed directly, unexpected results may occur.integer(integer) orfloat(floating-point number), crucial for ensuring accurate data processing and flexible display.

Understanding the difference between string numbers and actual numbers

Imagine that you might have a namedarchive.PriceThe field stores the product price, for example, "99.50". On the back-end interface, you see it as a price. But in the template, ifarchive.PriceIt is still treated as a string, then{{ archive.Price * 2 }}This operation may not perform multiplication as expected, or{% if archive.Price > 100 %}Such conditional judgment may fail due to string comparison rules (for example, the string "150" is less than "50" in lexicographical order).

To avoid such problems, the Anqi CMS template engine provides a powerful built-in filter that can conveniently convert string-type numbers to actual numeric types.

Core solution:integerandfloatFilter

The AnQi CMS template system has built-in two key filters, specifically designed to handle this data type conversion requirement:integer(Integer) andfloat(Floating-point number).

1.integerFilter: Convert to integer

When you need to convert a string number to a non-decimal integer,integerThe filter is a good choice. It will try to parse the string and return its integer part.

Usage:

You just need to add it to the variable you want to convert.|integer.

{{ 你的变量 | integer }}

Example:

Assumeitem.StockThe value is the string "123".

库存数量:{{ item.Stock | integer }}

This will output123.

Ifitem.ViewsThe value is the string '5.8', afterintegerThe filter will discard the decimal part, keeping only the integer:

浏览量:{{ item.Views | integer }}

This will output5.

It is worth noting that if the filter tries to convert a completely non-numeric string (such as “abc”), it will default to returning0.

2.floatFilter: Convert to float number

When you need to retain the decimal part of a number, or handle numbers that may contain decimal points,floatthe filter comes in handy. It will convert the string to a floating-point number type.

Usage:

Similarly, add to the end of your variable|floatJust do it.

{{ 你的变量 | float }}

Example:

Assumeitem.PriceThe value is a string "99.50".

产品价格:{{ item.Price | float }}

This will output99.500000(The specific number of decimal places may vary due to internal system accuracy, but it is already a floating-point type).

Ifitem.DiscountThe value is the string "0.8", then:

折扣:{{ item.Discount | float }}

This will output0.800000.

withintegerSimilarly, if:floatThe filter encounters a string that cannot be converted to a floating-point number (for example, "xyz"), it will default to returning0.0.

Application scenarios in practice

After understanding the basic usage of these two filters, let's see how they are actually used in templates:

  1. Perform arithmetic operations:Suppose you want to calculate the total price of the product, whereproduct.PriceMay be “120.50”,product.QuantityMay be “3”.

    {% set totalPrice = product.Price|float * product.Quantity|integer %}
    总价:{{ totalPrice }}
    

    So it can be calculated correctly,361.5.

  2. Conditional judgment based on numbers:You may want to display different styles based on the number of article views. Ifarchive.Viewsis the string “1500”, and you want to determine if it exceeds 1000:

    {% if archive.Views|integer > 1000 %}
        <span class="hot-article">热门文章</span>
    {% else %}
        <span>普通文章</span>
    {% endif %}
    

    Here, the comparison will be made by value.

  3. Formatted output to a specific number of decimal places:When displaying prices, we usually want to maintain a uniform number of decimal places, such as two. You canfloatFilter with other formatting filters (such asfloatformat) are used together.

    {% set displayPrice = item.Price|float|floatformat:2 %}
    显示价格:{{ displayPrice }}
    

    Ifitem.Priceis '123',displayPricewill be123.00; if it is '99.5',displayPricewill be99.50.

Chaining usage and precautions

These filters can be chained with other filters, for example|float|integeror|integer|floatIt should be noted that their execution order and specific data content will affect the final result.

  • "5.8" | float | integerIt will first convert '5.8' to a floating-point number.5.8, thenintegerThe filter will truncate it to.5.
  • "5.8" | integer | floatWill first convert '5.8' to an integer5(becauseintegerThen, the decimal will be discardedfloatThe filter will convert it to a floating-point number5.0.

In actual use, please be sure to choose the appropriate filter or combination according to your business logic to ensure the accuracy of data processing.At the same time, considering the uncontrollability of data input, when processing data from users or other external sources, it is best to always pre-convert the data types to avoid potential errors.

By flexible applicationintegerandfloatThe filter will allow you to more accurately control the numeric data in the Anqi CMS template, thereby realizing more powerful functions and more beautiful display effects.


Frequently Asked Questions (FAQ)

Q1: Why can't my numbers be directly added, subtracted, multiplied, or divided in the template?

A1:During the template rendering process of AnQi CMS, data obtained from the content model or database may be treated as strings by default when passed to the template, even if they represent numbers.The "number" cannot be directly performed mathematical operations for string type.For example, the result of concatenating the strings '5' and '2' could be '52' (string concatenation), not the number 7.|integeror|floatThe filter explicitly converts them to numeric types.

Q2: Can I convert a floating-point number string (such as "5.8") to an integer first, and then to a floating-point number? Will the result be 5.8 or 5.0?

A2:If you first use a floating-point number string (such as “5.8”),|integerthen process it with a filter, and then|floatprocess it with a filter again, the final result will be5.0This is becauseintegerWhen the filter converts a number to an integer, it will directlyTruncate(Discard) The decimal part instead of rounding. So '5.8' after|integerbecomes5, then after|floatit becomes5.0. If you need to keep the decimal and perform numerical calculations, please use directly|floatfilter.

Q3: If my string is not a number, like "free", what will|integeror|floathappen?

A3:When|integeror|floatThe filter attempts to convert a string that cannot be recognized as a number and defaults to returning a zero value. Specifically,|integerwill return0while|floatwill return0.0.This mechanism helps prevent template rendering interruption, but it also means that you need to be aware that if the data source may contain non-numeric values, they will be silently treated as zero, which may affect your calculation results or conditional judgments.