How to use `integer` and `float` filters to convert string numbers in Anqi CMS templates to numeric types that can be used in mathematical operations?

Calendar 👁️ 58

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.

Related articles

How to automatically add line numbers to code blocks or list content in `linenumbers` filter in Anqie CMS to enhance readability?

In daily content creation and website operations, we often need to insert code examples, configuration lists, or detailed operation steps in articles.The characteristic of this content is that it is multi-line text, and if line numbers can be automatically added to it, it will greatly enhance the reader's reading experience and the professionalism of the content.Imagine when you need to explain a part of the code to the reader, or guide them to complete a complex setup, you can accurately mention 'See line 5 of the code' or 'In step 3', this improvement in communication efficiency is self-evident.

2025-11-08

How to use the `linebreaks` and `linebreaksbr` filters to convert newline characters in the plain text content entered by an Anqie CMS user into HTML `<p>` or `<br>` tags?

In a content management system, processing plain text content entered by users and displaying it on the web page in the expected format is a common requirement.When the user enters text with line breaks in the back-end editor, the browser does not default to rendering it as HTML line breaks.All content may be squeezed onto one line, causing disordered layout and affecting reading experience.Fortunately, AnQiCMS provides a convenient template filter to solve this problem.

2025-11-08

What are the application scenarios and encoding differences of the `urlencode` and `iriencode` filters in the AnQi CMS template when encoding URL parameters?

In AnQiCMS template development, when handling URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS provides the `urlencode` and `iriencode` filters to help us complete this task, but their application scenarios and encoding differences are not the same.

2025-11-08

How to use the `first` and `last` filters to quickly get the title of the first or last article in the Anqi CMS article list?

In website operation, we often need to quickly extract some specific information from the article list, such as the homepage may need to display the latest article title, or in some special modules, it is necessary to obtain the title of the first or last entry in the article list.AnQiCMS (AnQiCMS) can easily meet these needs with its flexible template engine and rich filter functions.AnqiCMS's template system draws on the syntax of mainstream template engines like Django

2025-11-08

How to precisely control the decimal places of floating-point numbers using the `floatformat` filter in Anqi CMS, and how to implement rounding or specific rounding rules?

In a content management system, the clear presentation and precise control of data are crucial, especially when displaying amounts, percentages, or any floating-point numbers.AnQiCMS (AnQiCMS) provides a powerful template engine, where the `floatformat` filter is a powerful tool for handling the display of floating-point numbers.It can help us flexibly control the number of decimal places and implement different rounding rules according to the needs, making the digital data on the website both beautiful and accurate.

2025-11-08

How to use the `join` filter to concatenate the multiple tags (array) of an Anqi CMS article into a comma-separated string output?

AnQiCMS (AnQiCMS) is loved by website operators for its flexible and efficient features.In daily content management, articles or products often associate with multiple tags (Tag), which are stored in the system in the form of an array.When we need to display these tags on the front-end page, for example, showing

2025-11-08

How to use the `split` filter to convert the custom delimiter string returned by the Anqie CMS backend (such as "keyword1|keyword2") into an array for easy traversal?

In AnQi CMS content management practice, flexibility is the key to improving efficiency and achieving personalized display.Sometimes, we may encounter such a requirement: the backend returns a string of text separated by a special symbol through a custom field, such as a product introduction may have multiple related keywords, and it is stored as 'keyword1|keyword2|keyword3' such a format.How can I beautifully split this string of text into individual keywords and make them convenient for display or iteration in a front-end template?

2025-11-08

How to split a normal string into an array of individual characters using the `make_list` filter in the Anqi CMS template for more refined text processing?

In the world of AnQi CMS templates, we often need to process content in various ways, sometimes by paragraphs, sometimes by sentences, and sometimes, we need to refine the text more finely, down to every character.When conventional string processing methods fail to meet such refined needs, the `make_list` filter can excel, as it can split a common string into an array of individual characters, providing unprecedented flexibility for template designers.

2025-11-08