In AnQiCMS template development, we often encounter situations where we need to handle various types of data.Sometimes, even though the data retrieved from the database or entered by the user represents numbers, the system may treat it as a string type at the template layer.In this case, if we directly perform mathematical operations or numerical comparisons on these 'number strings', it may lead to unexpected results or even errors.Therefore, understanding how to convert a numeric string to an integer or floating-point number type in the AnQiCMS template is crucial for ensuring the accuracy and correctness of data processing.

AnQiCMS's template engine provides a rich set of filters (Filter), which can help us easily transform and process data. We mainly use them to convert numeric strings into specific numeric types.integerandfloatThese two filters.

Understand the necessity of type conversion

Imagine a scenario where you need to sort articles based on their 'reading volume' or calculate the 'total price' by multiplying the 'unit price' by 'quantity'. If fields such as 'reading volume', 'unit price', or 'quantity' are considered as strings in the template, then:

  • "100" + "50"may obtain"10050"instead of150.
  • "5" > "10"may be evaluated asTruebecause string comparison is performed character by character (‘5’ is greater than ‘1’), not numerical comparison.

By explicitly converting these strings to integers or floating-point numbers, we can ensure the execution of correct mathematical operations and logical judgments.

Convert string to integer: integerFilter

When you need to convert a numeric string to an integer, you can useintegera filter. This filter will try to parse the input value and return its corresponding integer form.

the syntax:

{{ 您的变量 | integer }}

Example demonstration:

Assuming you have a variableitem.CountIt may be a numeric string, you want to use it as an integer:

{% set stringNumber = "123" %}
{% set stringFloat = "5.8" %}
{% set stringText = "hello" %}

<p>字符串 "123" 转换为整数: {{ stringNumber | integer }}</p>
<p>字符串 "5.8" 转换为整数: {{ stringFloat | integer }}</p>
<p>字符串 "hello" 转换为整数: {{ stringText | integer }}</p>
<p>直接数字 456 转换为整数: {{ 456 | integer }}</p>

Expected output:

<p>字符串 "123" 转换为整数: 123</p>
<p>字符串 "5.8" 转换为整数: 5</p>
<p>字符串 "hello" 转换为整数: 0</p>
<p>直接数字 456 转换为整数: 456</p>

As can be seen from the example,integerThe filter automatically truncates the decimal part when converting floating-point numbers. If the input string cannot be parsed as a valid number (for example, “hello”), it will return0.

Convert string to float:floatFilter

When you need to convert a number string to a float (i.e., a number with a decimal point), you can usefloatA filter that tries to parse the input value and return its corresponding floating-point form.

the syntax:

{{ 您的变量 | float }}

Example demonstration:

Assuming you have a variableitem.PriceIt may be a numeric string, you want to calculate it as a floating-point number:

{% set stringNumber = "123" %}
{% set stringFloat = "5.8" %}
{% set stringText = "hello" %}

<p>字符串 "123" 转换为浮点数: {{ stringNumber | float }}</p>
<p>字符串 "5.8" 转换为浮点数: {{ stringFloat | float }}</p>
<p>字符串 "hello" 转换为浮点数: {{ stringText | float }}</p>
<p>直接数字 456 转换为浮点数: {{ 456 | float }}</p>

Expected output:

<p>字符串 "123" 转换为浮点数: 123.000000</p>
<p>字符串 "5.8" 转换为浮点数: 5.800000</p>
<p>字符串 "hello" 转换为浮点数: 0.000000</p>
<p>直接数字 456 转换为浮点数: 456.000000</p>

withintegerThe filter is similar, if the input string cannot be parsed as a valid number,floatthe filter will return0.000000.

combined use and precautions

In practical development, you may need to combine these two filters, for example, convert them to floating-point numbers first and then to integers to ensure that you round down, or perform more complex numerical processing.

For example, calculate the total price of the product:

{% set productPrice = "99.50" %} {# 可能是字符串 #}
{% set productQuantity = "3" %}  {# 可能是字符串 #}

{% set priceFloat = productPrice | float %}
{% set quantityInt = productQuantity | integer %}

<p>商品单价: {{ priceFloat }}</p>
<p>购买数量: {{ quantityInt }}</p>
<p>总价: {{ priceFloat * quantityInt }}</p>

Important reminder:

  • Data validation:When performing type conversion, always pay attention to the data source. If the input string is not a valid numeric format,integerwill return0,floatwill return0.0In critical business logic, you may need additional conditional judgments to handle these "invalid" values.0To avoid incorrect calculations.
  • Chaining operations:Filters can be chained, for example{{ "5.6" | float | integer }}Will be converted first5.6Then converted5.
  • Go Language's date format:Although it is not directly related to number conversion, the AnQiCMS backend is developed based on Go language, and the timestamp formatting function in the template (such asstampToDateFollow the time formatting rules of Go language, for example2006-01-02 15:04:05Familiarity with these rules helps better handle date and time data in templates.

By flexible applicationintegerandfloatThe filter allows you to ensure precise processing and display of numbers in the AnQiCMS template, thereby enhancing the robustness and user experience of the website.


Frequently Asked Questions (FAQ)

Q1: What will I get if I convert a string that is not a number?

A1:If you try to convert a string that cannot be parsed as a number (for example, “AnQiCMS”) to an integer or float,integerthe filter will return0,floatthe filter will return0.000000. This is a default error handling mechanism used to prevent template rendering from being interrupted.When processing user input or uncertain data, it is recommended to perform additional validation or default value settings.

Q2: How to format a floating-point number to a specific decimal place, such as retaining two decimal places?

A2:After converting to a floating-point number, you can usefloatformata filter to control the display of decimal places. For example,{{ 您的浮点数 | floatformat:2 }}It will format the floating-point number to retain two decimal places. If no digits are specified, it will try to intelligently format it by removing the trailing zeros.

Q3: Can the converted integer or floating-point number be used directly in mathematical operations and comparisons?

A3:Yes, once the numeric string passes throughintegerorfloatThe filter successfully converts to the corresponding numeric type, which can then be used directly in template mathematical operations such as addition, subtraction, multiplication, and division, as well as comparisons of size (for exampleif item.Value > 10Logical operations related to numerical counting and loops.