How to convert a numeric string (such as "5.5") to a floating-point number or integer for display and calculation in AnQiCMS template?

Calendar 👁️ 70

In AnQi CMS template development, we often encounter scenarios where we need to handle numeric string.For example, the price stored in the background custom field may be a text type "5.5", or the number may exist as a string in the data obtained through an external API.At this point, if you perform direct numerical calculations, problems may arise.However, AnqiCMS's template engine provides very flexible and powerful functions, which can easily convert numeric strings to floating-point numbers or integers and perform subsequent display and calculation.

Deep understanding of number processing in AnqiCMS template

AnqiCMS uses a syntax similar to the Django template engine, which makes it intelligent in processing data. When the template receives a variable that is itself a numeric type (for example, it has been defined in the Go backend code asint/float64E.g., you can directly perform arithmetic operations such as addition, subtraction, multiplication, and division in the template, for example{{ item.price * 0.8 }}To calculate the price after an 80% discount.

However, when data is passed in as a string, for example"5.5"Directly performing mathematical operations may result in unexpected results, even errors.AnqiCMS provides dedicated "Filters" for this, which act like "pipelines" in data processing, able to transform, format, or process data to meet our needs.

The core conversion tool:floatandintegerFilter

AnqiCMS template provides to safely convert numeric strings into computable values,floatandintegerthese two key filters.

  1. floatFilter: Convert to float numberWhen you need to convert a number string that may contain a decimal to a floating-point number,floatThe filter is a good choice. It will try to parse the string and if successful, it will return the corresponding floating-point value (for example5.5It will be converted into5.5). If the string cannot be parsed as a valid floating-point number (for example"foobar"It will return0.0This is very useful when handling potential error data.

    The usage is usually like this:

    {% set priceString = "5.5" %}
    {% set priceFloat = priceString|float %}
    <p>转换后的浮点数:{{ priceFloat }}</p> {# 输出 5.500000 #}
    
    {% set invalidString = "invalid_number" %}
    {% set invalidFloat = invalidString|float %}
    <p>无效字符串转换结果:{{ invalidFloat }}</p> {# 输出 0.000000 #}
    
  2. integerFilter: Convert to integerIf you are sure that the numeric string is an integer or want to truncate a floating-point number to an integer, thenintegerThe filter comes in handy. It will try to parse the string as an integer (for example"100"It will be converted into100)。If the string contains a decimal, it will round it down (for example"5.6"It will be converted into5)。Similarly, if it cannot be parsed as a valid number, it will return0.

    How to use:

    {% set countString = "100" %}
    {% set countInteger = countString|integer %}
    <p>转换后的整数:{{ countInteger }}</p> {# 输出 100 #}
    
    {% set floatString = "5.6" %}
    {% set floatToInteger = floatString|float|integer %} {# 先转浮点再转整数,得到 5 #}
    <p>浮点字符串转换为整数:{{ floatToInteger }}</p> {# 输出 5 #}
    
    {% set anotherInvalidString = "another_invalid" %}
    {% set anotherInvalidInteger = anotherInvalidString|integer %}
    <p>另一个无效字符串转换结果:{{ anotherInvalidInteger }}</p> {# 输出 0 #}
    

    It is worth noting that you can chain multiple filters together, just like abovefloatString|float|integerFor example, the data will pass through the processing of each filter in turn.

Perform numerical calculation

Once a numeric string has been successfully converted tofloatorintegertype, you can perform various arithmetic operations on it in the template.

For example, calculate the discounted price:

{% set originalPriceString = "100.50" %}
{% set discountRate = 0.75 %} {# 75折 #}

{% set convertedPrice = originalPriceString|float %}
{% set finalPrice = convertedPrice * discountRate %}
<p>最终价格:{{ finalPrice }}</p> {# 输出 75.375 #}

AnqiCMS also providesaddFilter, although it is more direct to use+the symbol for addition operation is usually more intuitive, butaddThe filter also provides an option in some scenarios (for example, when you need to add a known number with another variable that may not be a number, and ensure error handling).

{% set baseValue = 10 %}
{% set additionalString = "5" %}
{% set total = baseValue|add:additionalString|integer %} {# 10 + 5 = 15 #}
<p>使用add过滤器进行相加:{{ total }}</p> {# 输出 15 #}

Display and Format Numbers

After the numerical calculation is completed, we often need to format the result to make it more in line with display habits, such as retaining two decimal places.

  1. floatformatFilter: Control Decimal Places floatformatThe filter allows you to precisely control the number of decimal places in floating-point numbers. By default, it retains one decimal place, and if the last digit is 0, it is omitted. You can specify a specific number of places.

    {% set rawPrice = "75.375"|float %}
    <p>默认格式化:{{ rawPrice|floatformat }}</p> {# 输出 75.4 #}
    <p>保留两位小数:{{ rawPrice|floatformat:2 }}</p> {# 输出 75.38 #}
    <p>保留零位小数(四舍五入):{{ rawPrice|floatformat:0 }}</p> {# 输出 75 #}
    
  2. stringformatFilter: Advanced FormattingFor more complex number formatting needs, such as adding thousand separators, currency symbols, or padding zeros,stringformatThe filter provides powerful Go languagefmt.Sprintf()formatting capabilities of style.

    {% set totalAmount = "12345.678"|float %}
    <p>货币格式化:{{ totalAmount|stringformat:"$%.2f" }}</p> {# 输出 $12345.68 #}
    <p>整数填充:{{ 5|stringformat:"%03d" }}</p> {# 输出 005 #}
    

Comprehensive example

Assuming you have a product, its priceitem.priceIt is transmitted from the backend but may be a string, inventoryitem.stockIt is also a string, you need to display the discounted price on the page and check if the inventory is sufficient.

{% set itemPriceString = "128.99" %}
{% set itemStockString = "5" %}
{% set minStockRequired = 3 %}

{# 转换为数值类型 #}
{% set price = itemPriceString|float %}
{% set stock = itemStockString|integer %}

{# 进行计算 #}
{% set discountedPrice = price * 0.90 %} {# 九折 #}

<p>商品原价:{{ price|floatformat:2 }} 元</p>
<p>九折后价格:{{ discountedPrice|floatformat:2 }} 元</p>

{# 进行条件判断 #}
{% if stock > 0 %}
    <p>当前库存:{{ stock }} 件</p>
    {% if stock >= minStockRequired %}
        <p>库存充足,欢迎购买!</p>
    {% else %}
        <p>库存紧张,请尽快下单!</p>
    {% endif %}
{% else %}
    <p>商品已售罄。</p>
{% endif %}

By flexible applicationfloatandintegerFilter, combining arithmetic operators andfloatformat/stringformatThe display filter, you can easily handle the processing of numeric strings in the AnqiCMS template, and implement various complex display and calculation logic.


Frequently Asked Questions (FAQ)

  1. Why do I need to convert a string number to a floating-point number or an integer specifically? Can't the AnqiCMS template engine recognize it automatically?Answer: When AnqiCMS's template engine handles literal numbers, for example{{ 10 + 5 }})Can automatically recognize. But when the data source is a variable, and the value of the variable is a string that looks like a number (such as"5.5"),the template engine will usually treat it as plain text. To ensure the accuracy of subsequent mathematical operations or comparisons, it is explicitly usedfloatorintegerFiltering and conversion is a practice that can avoid errors caused by mismatched data types.

  2. **Question: If my numeric string contains non-numeric characters

Related articles

How to use `truncatechars` or `truncatewords` filters to truncate long text or HTML content and add an ellipsis?

In website content management, we often encounter such situations: in order to maintain the neat and unified layout of the page, we need to truncate the long text content without destroying its semantics or layout.Whether it is an article summary, product introduction, or user comment, appropriately controlling the length of the text and adding ellipses can greatly enhance the user experience.The template engine of AnQiCMS provides us with two very practical filters: `truncatechars` and `truncatewords`, as well as their variants for handling HTML content

2025-11-07

How to use the `stampToDate` filter to format a timestamp into a readable date format in AnQiCMS template?

In AnQiCMS (AnQiCMS) template development, we often encounter the need to convert timestamp data stored on the back-end into a clear and readable date and time format on the user interface.The original timestamp, for example `1609470335`, has no meaning to ordinary users.In order to enhance the user experience of the website, it is particularly important to display time information appropriately.Luckyly, AnQiCMS provides a very practical built-in filter——`stampToDate`, which can help us easily achieve this goal.

2025-11-07

How to get and display the content and information of a single page (such as "About Us" or "Contact Us") in AnQiCMS template?

Manage and display single-page content in AnQi CMS, such as "About Us", "Contact Us", or "Terms of Service", which is a very common requirement in website operation.AnQi CMS provides developers with intuitive and powerful template tags, allowing you to easily retrieve and display information on the front end of the website.Understanding Single Page Content Management in AnQi CMS Firstly, we need to understand how AnQi CMS manages these 'single pages'.In the "Page Resources" module in the background, you can find the "Page Management" feature.

2025-11-07

How does AnQiCMS handle and display image resources, including automatic compression, conversion to WebP format, and watermark management?

In website content operation, images are indispensable elements to attract visitors and convey information, but their size, loading speed, and copyright protection are also focuses for operators.AnQiCMS as a content management system is well-versed in this field, therefore, it has integrated a series of intelligent image resource processing and optimization functions, aiming to help us manage website images more efficiently and effortlessly, and improve user experience and SEO performance.

2025-11-07

How to use the `cut` or `removetags` filter to remove specific characters or HTML tags from strings in the AnQiCMS template?

In AnQi CMS template design, in order to better control the display of content, the system provides a variety of flexible filters (Filter).These filters can help you perform various string processing operations when outputting variables, such as removing specific characters or HTML tags, making the content neater and meeting your display requirements.Today, we will focus on the practical filters `cut` and `removetags`.

2025-11-07

How to use the `default` filter to set a default display value for possibly empty variables?

In website content management, we often encounter a situation where a certain data variable may not have a value on some pages or under certain conditions, that is, "empty".If the template directly outputs these blank variables, ugly gaps will appear on the page, which not only affects the aesthetics but may also confuse the visitor.In order to avoid such embarrassment, AnQi CMS provides a very practical tool - the `default` filter, which can help us set a graceful default display value for these variables that may be empty.

2025-11-07

How to perform simple arithmetic operations (+ - * /) and display the results in AnQiCMS template?

In AnQiCMS templates, we often need to display website content and data.But sometimes, we not only need to display stored data, but also need to process this data in some simple ways, such as calculating the total price of goods, statistics page loading progress percentage, or adding a certain number of values, etc.

2025-11-07

How to configure the pseudo-static URL rule in AnQiCMS to optimize the display path and SEO friendliness?

In website operation, the URL is not only the address of the page content, but also an important part of search engine understanding, user identification, and brand building.A clear and meaningful URL structure, known as "pseudo-static" or "staticized" URL, is crucial for improving the SEO performance and user experience of a website.AnQiCMS is a content management system that focuses on SEO-friendliness and provides flexible and diverse static URL configuration features, helping us optimize the display path of content better.

2025-11-07