In AnQiCMS template, how to convert a string number into an actual `integer` or `float` type?

Calendar 👁️ 68

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.

Related articles

How to find the first occurrence index of a character or substring in the AnQiCMS template?

During the process of displaying website content or template development, we often encounter situations where we need to process specific text, such as checking if a keyword exists or locating the first occurrence of a character or substring.The template engine of AnQiCMS (AnQiCMS) provides a series of powerful filters (Filters) to help us complete these tasks efficiently.Today, let's discuss how to use the `index` filter to accurately find the position index of the first occurrence of a character or substring in the AnQiCMS template.Understand

2025-11-08

How to extract specific number information from a long numeric string in AnQiCMS template?

In website operations, we often encounter scenarios where we need to handle some structured long numeric string.For example, a product code may contain the production date and batch information; an order number may imply regional codes and serial numbers; or may be a unique identifier generated by specific business logic.These long digital strings often carry rich metadata, and we may only need the numerical information at specific positions for display, filtering, or further processing.

2025-11-08

How to precisely control the display of floating-point numbers in the AnQiCMS template, such as retaining two decimal places?

In website content operation, the way numbers are presented often affects user experience and the accuracy of information.Especially for floating-point numbers, such as product prices, statistics, and ratings, it is common to require accuracy to several decimal places or rounding according to business needs.AnQiCMS is a powerful template system that provides us with a flexible way to handle these data.Today, let's delve into how to efficiently and accurately control the display of floating-point numbers in the AnQiCMS template.

2025-11-08

How to split a line of text content (such as a tag string) into an array of individual words for processing in AnQiCMS?

In the practice of AnQiCMS content management, we often encounter scenarios where it is necessary to split a seemingly simple line of text into smaller, more independent 'words' for fine-grained processing.For example, the document tag (Tag), keyword list, or multiple values separated by a specific symbol in custom fields.The core of this requirement lies in converting a string into an array that can be traversed and manipulated individually.

2025-11-08

How to concatenate the tag array in AnQiCMS template into a string with a custom delimiter?

In AnQiCMS template development, we often need to display a set of data obtained from the database, such as the multiple tags (Tags) of articles, in a user-friendly manner rather than simply listing them.One of the most common needs is to concatenate these tags into a string with a custom separator, such as AnQiCMS's powerful template engine provides a flexible way to achieve this goal.

2025-11-08

How to get the total length of elements in a string, array, or key-value pair in AnQiCMS template?

In AnQi CMS template design, dynamically obtaining the total length of elements in a string, array, or key-value pair is a very practical feature. It can help us flexibly display information on the page, such as showing the number of products, the number of comments, or adjusting the layout according to the content length.The Anqi CMS template engine provides simple and efficient filters to meet these requirements.### Core Tool: `length` Filter The most direct and universal method to obtain the total number of elements in any string, array (slice), or key-value pair (map/struct) is to use

2025-11-08

How does the AnQiCMS template automatically convert line breaks in text to HTML tags such as `<p>` or `<br>`?

In website content presentation, text formatting is often the key to determining the user's reading experience.We often encounter such needs: the text content obtained from the background database usually only contains simple newline characters (`\n`), and if it is displayed directly on the web page, the browser will not intelligently convert these newline characters into the HTML paragraph (`<p>`) or line break (`<br>`) tags we expect, causing the content to be cramped together and lose its original structure and readability.AnQiCMS (AnQiCMS) has fully considered this point in template design

2025-11-08

How to dynamically define and use small array variables for loops in AnQiCMS templates?

In AnQiCMS template development, we often need to flexibly display some small data sets according to business logic.These collections may be some custom tags, navigation items, or just some status identifiers.Although AnQiCMS provides rich tags to call background data, sometimes we want to define a small array directly in the template and loop through it to achieve finer control and simpler template code.

2025-11-08