In website operation, we often encounter the need to handle numerical 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 a total calculation of these prices in a template (such as order total) directly adding the strings will result in unexpected results (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 this kind of data conversion and calculation problems very flexibly.
Understand the price data in custom fields.
AnQiCMS allows us to customize content models according to business needs, which means we can add various additional fields to articles, products, and other content.When creating these custom fields, we can choose different field types, such as 'single-line text', 'numbers', etc.If we accidentally or for a specific purpose choose to store price information in the 'Single Line Text' type, then even if the content entered is pure numbers, what we get in the template will be a string.
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 }}The text obtained is '99.99', not a number that can be used for calculation.
Core step one: Convert the string price to a number.
AnQiCMS template engine includes several practical filters, specifically designed for data type conversion, among whichfloatandintegeris the key to handling price conversion.
floatFilter:When your price may include decimals (such as 199.50),floatthe filter is a good choice. It will try 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, if the string is "free"), it will default return
0.0This is very useful in handling exceptional data, as it can prevent template errors.
- Usage example:
integerFilter:If your price is always an integer (like 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 a string contains a decimal (such as "99.99"),
integerthe filter will truncate the decimal part, only retaining the integer (i.e., getting99Therefore, unless you explicitly do not need decimals, it is usually recommended to use when handling pricesfloat. - with
floatSimilarly, a return will occur when conversion fails0.
- Usage example:
Choose based on whether your price data contains decimals or notfloatorintegerFiltering is crucial. It is recommended to use for scenarios involving currencyfloatto retain accuracy.
Core step two: perform numerical calculations and format the display
Once we convert the string price to a number, we can use the arithmetic calculation capability of the AnQiCMS template to sum up.
addFilter performs addition operation:addThe filter can conveniently add two numbers together. 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 numerical addition.- Usage example:
{% set result = price1|add:price2 %}
- Usage example:
The template directly supports arithmetic operations:except
addFilters, the template engine of AnQiCMS also directly supports+,-,*,/Basic arithmetic operators, which enable complex computation logic to be implemented in templates.- Usage example:
{% set total = price1 + price2 * quantity %}
- Usage example:
floatformatFilter formatted output:After the price calculation is performed, 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 (such as214.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's take a specific example to show how to convert a string price from a custom field to a number and calculate the total order amount.
Assuming our "product" content model has two custom fields:
single_product_price: Product price, stored as a string, for example "199.50".shipping_fee: Shipping fee, 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 {# Assuming we are on a document detail page, we 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. Obtain the 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, such as {% set shippingFee = shippingFeeStr|default:“0”|float %} #}
{# 3. Perform total calculation #} {% set totalAmount = productPrice|add:shippingFee %} {# Or use arithmetic operators directly: {% set totalAmount = productPrice + shippingFee %} #}
Order Details
Product Price:¥{{ productPrice|floatformat:2 }}
Shipping Fee:¥{{ shippingFee|floatformat:2 }}
Order Total: ¥{{ totalAmount|floatformat:2 }}
{# 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 `