During the template development process of AnQi CMS, we often encounter scenarios where we need to perform arithmetic operations on numbers, such as calculating the total price of goods, comparing inventory quantities, or displaying different contents based on specific numbers.However, sometimes the data obtained from the background, even though it looks like a number, may exist in the form of a string in the template, which makes it impossible to perform mathematical operations directly.This is provided by Anqi CMS at this timeintegerandfloatThe filter is particularly important, as it helps us convert these string numbers into truly usable numeric types for calculation.

Understanding the problem: why do we need to convert?

Imagine that you might have set up a custom field named 'Product Price' in the content model, and the user entered '99.99'.When you try to use directly in the template{{ item.Price * 2 }}When performing calculations, you may find that the results are not as expected, even causing template errors.This is because the template engine recognizes "99.99" as a string rather than a computable number.Data stored in databases or custom fields is often like this, they require explicit type conversion to participate in mathematical operations.

The solution of Anqi CMS:integerandfloatFilter

To solve this problem, Anqi CMS provides a pair of very practical filters:integerUsed to convert values to integers,floatUsed to convert values to floating-point numbers (i.e., decimals).

integerFilter: Convert string to integer

When we need to deal with values such as product quantity, product ID, article views, and other numbers that do not require decimal parts, integerThe filter can be used. It will try to convert the input value to an integer.

Use case example:Suppose we take a field fromitem.ViewsThe viewed count is the string “12345”, and we want to perform addition or comparison on it in the template.

Code example and its output:

{# 假设 item.Views 的值为字符串 "12345" #}
<div>今天的浏览量是:{{ item.Views|integer }}</div>
<div>明天预期的浏览量是:{{ item.Views|integer + 100 }}</div>
{# 假设 item.Id 的值为字符串 "5" #}
{% if item.Id|integer > 3 %}
    <div>这是一个热门商品!</div>
{% endif %}

Output example:

今天的浏览量是:12345
明天预期的浏览量是:12445
这是一个热门商品!

IfintegerThe filter tries to convert a completely non-numeric string (such as 'foobar' or a null valuenothing), and it will convert it to an integer0If a string is a floating-point number (such as "5.4" or "5.6"), it will first convert it to a floating-point number and then truncate it (discarding the decimal part without rounding), for example, "5.4" and "5.6" will both become5.

floatFilter: Convert string to float

When dealing with values such as product prices, discount percentages, and other numbers that require decimal places,floata filter is an ideal choice. It will convert the input value into a floating-point number.

Use case example:If we have a custom fielditem.PriceStored the product price as a string "99.99", oritem.DiscountStored the discount percentage as a string "0.8".

Code example and its output:

{# 假设 item.Price 为字符串 "99.99",item.Discount 为字符串 "0.8" #}
<div>商品原价:{{ item.Price|float }}</div>
<div>打折后的价格:{{ item.Price|float * item.Discount|float }}</div>
{# 假设 item.Weight 为字符串 "1.5" #}
{% if item.Weight|float < 2.0 %}
    <div>这是轻量级商品。</div>
{% endif %}

Output example:

商品原价:99.99
打折后的价格:79.992
这是轻量级商品。

withintegerSimilarly, if:floatThe filter tries to convert a non-numeric string and it will return a floating-point number0.0. The input of numeric type will also be correctly converted to a floating-point number. It is worth noting that,floatThe filter can be used withintegeruse in combination, for example{{ "5.6"|float|integer }}Will first convert '5.6' to a floating-point number 5.6, and then to an integer 5.

Application in practice: Make your template come to life.

MasteredintegerandfloatAfter the filter, you can perform more complex logical judgments and numerical calculations in the Anqi CMS template.

For example, display prices with units:

{# 假设 item.Price 为字符串 "120.50",item.Quantity 为字符串 "3" #}
{% set total_price = item.Price|float * item.Quantity|integer %}
<div>
    商品名称:{{ item.Title }}<br>
    单价:¥{{ item.Price|float|floatformat:2 }}<br>
    数量:{{ item.Quantity|integer }}件<br>
    总价:¥{{ total_price|floatformat:2 }}
</div>

By|floatformat:2Filter, we can also format floating-point numbers to retain two decimal places.

Points to note

AlthoughintegerandfloatThe filter provides a convenient type conversion feature, but we also need to pay attention to the following points when using it:

  • Data source reliabilityEnsure that the string you are trying to convert is indeed a number, even if it contains non-numeric characters, and also have a psychological expectation that it will be converted to0.
  • ChainingThese filters can be chained, for example{{ "100"|integer + 20|float }}They will be executed from left to right.
  • Default behaviorUnderstand the default return value when the conversion fails (for example, converting "abc" to an integer), which helps you handle it in the template and avoid unexpected situations.

By flexible applicationintegerandfloatThe filter, your Aiqi CMS template will become more powerful and dynamic, capable of easily handling various numerical processing needs, making the website functions more perfect.


Frequently Asked Questions (FAQ)

Q1: If a string contains non-numeric characters,integerorfloathow will the filter handle it?A1: If a string contains non-numeric characters (for example, "abc", "123a"),integerthe filter will convert it to0,floatthe filter will convert it to0.0This means that even if part is a number, if there is any non-numeric character, the entire conversion will fail and return the default value.

Q2: Can I directly useifused in a statementintegerorfloatfilter?A2: Can. When you areifWhen these filters are used in statements, they will convert the strings to the corresponding numeric types, thenifThe statement will compare or judge based on the converted numeric values. For example{% if item.Stock|integer < 10 %}.

Q3:integerandfloatCan the value converted by the filter be directly calculated with other numbers?A3: Yes, once the string passes throughintegerorfloatThe filter successfully converts to a numeric type, at which point they are completely equivalent to the other numbers in the template, and can perform all mathematical operations such as addition, subtraction, multiplication, and division, and can also be mixed with values that are already numeric without conversion.