How can I convert a string price from a custom field into a number that can be used in the order total in the template?

Calendar 👁️ 61

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.

  1. 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 return0.0This is very useful in handling exceptional data, as it can prevent template errors.
  2. 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.
    • withfloatSimilarly, a return will occur when conversion fails0.

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.

  1. 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 %}
  2. The template directly supports arithmetic operations:exceptaddFilters, 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 %}
  3. 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.

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 `

Related articles

How can I perform numerical calculations based on a user-defined parameter (string)?

During website operation, we often encounter scenarios where we need to perform calculations on custom data, such as dynamically calculating prices based on product parameters, displaying rating statistics, or performing other numerical processing based on user input or content attributes.AnQi CMS provides us with the ability to meet these requirements with its flexible content model and powerful template engine.This article will introduce in detail how to perform numerical calculations based on custom string parameters in Anqi CMS.### First Step: Preparation - Define Your Custom Parameters First

2025-11-08

How to display product prices in AnQiCMS templates and control decimal places?

In website operation, the display of product prices is a crucial link, not only to ensure the accuracy of information, but also to ensure that the presentation method conforms to the reading habits and brand image of users.AnQiCMS with its flexible template system, provides users with powerful customization capabilities, allowing you to easily control the display of product prices, including decimal places.### How to get product price: Where does it come from? In the AnQiCMS template, the product price is usually stored and called as a field of the document (Article or Product)

2025-11-08

Which formatting placeholders does the `stringformat` filter support?

In AnQiCMS template development, in order to better display and control the presentation of data on the page, we often need to format variables.Among them, the `stringformat` filter is a very practical tool that allows us to convert numbers, strings, or other types of values into a specific string format according to predefined rules.The strength of this filter lies in its adoption of the placeholder syntax of the Go language `fmt.Sprintf()` function, making the control of output format flexible and accurate

2025-11-08

How to format numbers, strings, and any other values to output as strings in a specific format (`stringformat`)?

In the display of website content, we often need to present different types of data (such as numbers, strings, and even more complex structures) in a unified and precise manner on the page.The template engine of AnQiCMS provides powerful tools, one of which is a very practical feature called `stringformat` filter, which can help us format any value into a string of a specific format.When we retrieve data from the backend, whether it is the number of views of an article, the price of a product, or user-defined parameters, they may be represented by numbers

2025-11-08

How to dynamically adjust the decimal precision of displayed numbers in a template?

In website content operation, the precise display of numbers is often crucial, whether it is product prices, statistical data, or technical indicators, the accuracy of decimal point display directly affects the accuracy of information and the understanding of users.AnQiCMS provides a flexible template engine that allows us to easily adjust the decimal precision of numbers in frontend templates, thus satisfying various complex display requirements.The AnQiCMS template system is developed based on Go language, with a syntax style similar to Django, it offers powerful Filter (Filter) functions

2025-11-08

How does `floatformat` prevent the display of the decimal part when a floating-point number is exactly an integer (such as 10.00)?

In website content operation, we often encounter situations where we need to display numbers.These numbers may come from a floating-point type in a database, but in some cases, when they are exactly integers (such as `10.00`, `50.0`), we want them to be presented in a more concise integer form, such as `10` or `50`, rather than with unnecessary decimal parts.AnQiCMS (AnQiCMS) provides powerful template tags and filters, where the `floatformat` filter is a powerful tool to solve such problems

2025-11-08

How to perform complex mathematical expression calculations in templates, such as exponentiation or multi-step operations?

In website content management, we often need to handle various data, and this data is not always in its final form.Sometimes, we need to perform simple addition, subtraction, multiplication, and division in templates, and sometimes even more complex mathematical operations, such as calculating squares, cubes, or handling complex expressions with multiple steps.For AnQiCMS users, the good news is that its template engine provides very flexible and powerful mathematical calculation capabilities, allowing us to easily meet these needs.The template system of AnQiCMS is based on Django template engine syntax

2025-11-08

How to extract part of the numbers from a long ID string for display or logical judgment?

In website operations, we often encounter the need to handle various long string IDs, such as product SKUs, order numbers, user IDs, etc.These ID strings usually contain multiple segments of information, and we may only need part of the numbers for displaying on the page, statistics for reports, or for some business logic judgments.AnQiCMS (AnQiCMS) strong template engine provides us with flexible tools, making it easy to meet such needs.### AnQiCMS template string processing tool: Filter AnQiCMS

2025-11-08