In website operation, we often encounter the need to handle numeric data such as product prices or service fees.This data is sometimes stored in custom fields, but for various reasons, they may be saved in the form of strings (text), such as "199.50 yuan" or "150".When we need to perform summation calculations on these prices in a template (such as order total), directly adding the strings will result in unexpected outcomes (such as “199.5015.00” instead of “214.50”).This is when you need to convert these string prices into actual numbers in order to perform correct mathematical operations.
AnQiCMS provides powerful template tags and filters, which can handle such data conversion and calculation problems very flexibly.
Understand the price data in custom fields
AnQiCMS allows us to customize content models according to business requirements, which means we can add various additional fields for articles, products, and other content.When creating these custom fields, we can choose different field types, such as 'Single line text', 'Number', and so on.If we inadvertently or for specific purposes choose the 'Single-line text' type to store price information, then even if the content entered is purely numeric, the string will be obtained in the template.
For example, you may have created a custom field namedproduct_price_strand entered '99.99'. Refer to it directly in the template.{{ archive.product_price_str }}得到的就是文本“99.99”,而不是一个可以用来计算的数字。
核心步骤一:将字符串价格转换为数字
AnQiCMS template engine built-in several practical filters, specifically used for data type conversion, wherefloatandintegeris the key to our price conversion.
floatFilter:When your price may include a decimal (such as 199.50),floatthe filter is the ideal choice. It will attempt to convert the string to a floating-point number.- Usage example:
{{ "99.99"|float }}you will get a number99.99. - If the conversion fails (for example, the string is "free"), it will return by default
0.0This is very useful when handling exceptional data, as it can prevent template errors.
- Usage example:
integerFilter:If your price is always an integer (such as 150),integerthe filter is more suitable. It will try to convert the string to an integer.- Usage example:
{{ "150"|integer }}you will get a number150. - If the string contains a decimal (such as “99.99”),
integerthe filter will truncate the decimal part, only retaining the integer (i.e., getting99)。Therefore, it is usually recommended to use when handling prices unless you explicitly do not need decimalsfloat. - With
floatSimilarly, it will return an error when the conversion fails0.
- Usage example:
Choose based on whether your price data contains decimalsfloatorintegerFilter is crucial. For scenarios involving currency, it is usually recommended to use.floatTo retain accuracy.
Core step two: perform numerical operations and format the display.
Once we convert the string price to a number, we can use the arithmetic operation capability of the AnQiCMS template to sum up.
addAddition operation by the filter:addThe filter can easily add two numbers.It can handle the addition of mixed integers, floating-point numbers, and even strings, but after we have converted them to numbers, it will perform precise numeric addition.- Usage example:
{% set result = price1|add:price2 %}
- Usage example:
Template directly supports arithmetic operations:Except
addFilters, the template engine of AnQiCMS also directly supports+,-,*,/Basic arithmetic operators, which allows complex calculation logic to be implemented in the template.- Usage example:
{% set total = price1 + price2 * quantity %}
- Usage example:
floatformatFilter format output:After the price calculation, it is usually necessary to format the result into a standard currency format, such as retaining two decimal places.floatformatThe filter can achieve this.- Usage example:
{{ total|floatformat:2 }}The number will be formatted as a string with two decimal places (e.g.,214.50)。If the number is214,floatformat:2it will also be output214.00.
- Usage example:
Practical exercise: Calculate the total order amount in the template
Let us demonstrate how to convert a string price obtained from a custom field into a number and calculate the total order amount with a specific example.
假设我们的“product”内容模型有两个自定义字段:
single_product_price:product unit price, stored as a string, for example “199.50”.shipping_fee:Shipping cost, stored as a string, for example, “15.00”.
Now, we want to display this information on the order details page and calculate the total price.
”`twig {# Assume we are on a document detail page and need to retrieve the custom price field of the document #}
{# 1. Get the product unit price and convert it to a number using the float filter #} {% archiveDetail productPriceStr with name=“single_product_price” %} {% set productPrice = productPriceStr|float %} {# If the custom field may be empty, you can add a default value, for example {% set productPrice = productPriceStr|default:“0”|float %} #}
{# 2. Get shipping fee and convert it to a number using the float filter #} {% archiveDetail shippingFeeStr with name=“shipping_fee” %} {% set shippingFee = shippingFeeStr|float %} {# If the custom field may be empty, you can add a default value, for example {% set shippingFee = shippingFeeStr|default:“0”|float %} #}
{# 3. Execute total calculation #} {% set totalAmount = productPrice|add:shippingFee %} {# Or use arithmetic operators directly: {% set totalAmount = productPrice + shippingFee %} #}
Order Details
Product Unit Price:¥{{ productPrice|floatformat:2 }}
Shipping Fee:¥{{ shippingFee|floatformat:2 }} English
订单总计: English¥{{ totalAmount|floatformat:2 }} English
{# If you need to calculate the total price of multiple products and these products are in the list, you can do it like this #} {# Assuming there is a product list variable `