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.
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 #}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 above
floatString|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.
floatformatFilter: Control Decimal PlacesfloatformatThe 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 #}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)
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.**Question: If my numeric string contains non-numeric characters