How to ensure that the price string in a custom field is correctly calculated?

Calendar 👁️ 64

In AnQiCMS (AnQiCMS), using custom fields flexibly to manage various content, including product prices, service fees, and other numerical information is an important aspect for enhancing the personalization and functionality of the website.However, when using these price data, we often need to calculate or format it in a specific way, such as calculating the total price, applying discounts, or simply displaying it as currency with two decimal places.Ensure these operations are executed correctly, we need to pay attention to several key steps.

The basics of custom fields: choose the correct data type

Firstly, everything starts with the settings you make when creating custom fields in the Anqi CMS backend. When you intend to let the price data stored in a field participate in mathematical operations, be sure to select this field in the content model.“Number”Type, not the default “Text line”.

  • Select “Number” typeIn the background, go to 'Content Management' under 'Content Model', select the model you need to edit (such as 'Product Model'), and then when adding or editing fields in 'Content Model Custom Fields', set the 'Field Type' to 'Number'.This ensures that AnQiCMS will store data in numeric format when storing data, thereby laying the foundation for subsequent calculations.
  • Avoid storing price in “Text line”.If the price is stored as 'single-line text', even if you enter pure numbers, the system will treat it as a string.This means that performing direct addition, subtraction, multiplication, or division operations on it may not yield the expected results and may even cause errors.

So, planning in the design phase of custom fields is the first step to ensure that the price can be calculated correctly.

Get price data in the template.

Whether you are getting the built-in price field of AnQiCMS (such asarchive.Price) or a custom price field (such asproductPrice), you can use it in the templatearchiveDetailorarchiveParams.

  • Get built-in price field:
    
    {{ archive.Price }}
    
  • Retrieve a custom price field (for example namedactualPrice): If you create a custom field by directly using the field name (such asactualPrice), you can retrieve it like this:
    
    {% archiveDetail with name="actualPrice" %}
    
    Or, if you are usingarchiveParamsLoop to retrieve, need to find the correspondingFieldNameitem:
    
    {% archiveParams params %}
    {% for item in params %}
        {% if item.FieldName == "actualPrice" %}
            <div>实际价格:{{ item.Value }}</div>
        {% endif %}
    {% endfor %}
    {% endarchiveParams %}
    
    at this point,item.Valuewill include the price you entered.

Convert the price string to a computable number.

Even if you set the custom field to 'numeric' type in the background, or in some special cases, the price data is still in string format, we can use the filters provided by AnQiCMS to perform type conversion to ensure they can participate in calculations. Here, the main use isfloatandintegerfilter.

Prices usually contain decimals, thereforefloatThe filter will convert strings to floating-point numbers, which is more common when dealing with currency. If your prices are always integers, you can useinteger.

For example,item.ValueIs a string representation of the price '99.99', usingfloatFilter conversion:

{% set price_value = item.Value|float %}

To enhance the robustness of the template and prevent errors when the price field is empty or contains non-numeric characters, we can combinedefaultFilter, set a default value for it (usually 0 or 0.0):

{% set price_value = item.Value|float|default:0.0 %}

So, even ifitem.ValueIt is empty,price_valueWill also be set securely to0.0To avoid calculation errors.

Perform price arithmetic operations

Once the price data is ensured to be of numeric type, we can make use of the arithmetic calculation capabilities of the AnQiCMS template to perform calculations. The AnQiCMS template supports direct mathematical expressions and can also useaddApply filters for more specific operations.

  • Basic arithmetic operations: You can use common operators such as addition (+), subtraction (-), multiplication (*), and division (/) in the template.

    Assume you want to calculate the total price including tax, with a tax rate of 13%:

    {% set unit_price = archive.Price|float|default:0.0 %}
    {% set quantity = 2 %} {# 假设数量为2件 %}
    {% set subtotal = unit_price * quantity %}
    {% set tax_rate = 0.13 %}
    {% set tax_amount = subtotal * tax_rate %}
    {% set total_price = subtotal + tax_amount %}
    
  • UseaddFilter: For simple addition operations,addthe filter also provides a convenient way.

    {% set base_price = 100.00 %}
    {% set shipping_cost = 10.50 %}
    {% set final_price = base_price|add:shipping_cost %}
    

Formatted price display

After calculating the final price, it is usually necessary to format it better for the user, such as retaining two decimal places and adding a currency symbol.floatformatandstringformatThe filter is very useful in this regard.

  • floatformatUsed to retain decimal places: If you need to converttotal_priceRetain two decimal places:

    {{ total_price|floatformat:2 }} {# 例如输出 226.00 #}
    

    floatformatThe filter can also intelligently handle numbers, such as{{ 226.00|floatformat }}It will output.226(without decimal),{{ 226.50|floatformat }}It will output.226.5(Round to one decimal place). When you need to strictly retain a certain number of decimal places, please enter the specific number.

  • Combined with currency symbols andstringformatTo add a currency symbol, you can directly concatenate strings in the template, or you can also make use ofstringformatto achieve more flexible formatting.

    {# 直接拼接 #}
    <span>总价:¥ {{ total_price|floatformat:2 }}</span>
    {# 使用 stringformat #}
    <span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>
    

    Here%.2fRepresents formatting a floating-point number to two decimal places.

By following these steps, from creating custom fields, data retrieval, type conversion, to the final calculation and formatting, you can ensure the correct calculation and elegant display of custom price strings in Anqi CMS.


Frequently Asked Questions (FAQ)

Q1: Why am I entering numbers in custom fields, but when performing addition operations in the template, the result is string concatenation instead of numerical addition?

A1:This is likely because you set the 'field type' to 'single line text' instead of 'number' when creating custom fields in the background.Single-line text" type will treat any content you input as a string."}To solve this problem, it is recommended that you change the type of this custom field to 'number'.If the field type cannot be changed or for other reasons it is necessary to use "Single Line Text", then after obtaining the value of the field in the template, it is necessary to use|floator|integerThe filter explicitly converts it to a numeric type, for example{{ item.Value|float|add:other_value }}.

Q2: How can you ensure that the price is always displayed with two decimal places and a currency symbol in the template?

A2:You can usefloatformatorstringformatFilter to achieve this purpose.

  • UsefloatformatManually add the currency symbol afterwards:<span>总价:¥ {{ total_price|floatformat:2 }}</span>.
  • UsestringformatCan be done in one go:<span>总价:{{ total_price|stringformat:"¥ %.2f" }}</span>.%.2fSpecified to be formatted as a floating-point number and retain two decimal places.

Q3: If my price field may be empty or not filled in some documents, will it cause the template to error? How should I handle it?

A3:Yes, if the price field is empty or contains non-numeric content, directly performing the calculation may cause the template to error. To avoid this situation, you can combine the use ofdefaultSet a default safe value for the filter, for example0.0So when the price field actually has no value, it will be replaced with0.0to ensure the smooth operation of calculations. For example:{% set safe_price = archive.Price|float|default:0.0 %}.

Related articles

How can I implement a continuous conversion from string to floating-point number to integer in the template?

In website template development, we often encounter situations where data type conversion is required.For example, you may retrieve a number stored as a string from a database, but you need to perform mathematical calculations on it or use it as an index for a loop, which requires converting it to a floating-point number or even an integer.The template engine of AnQiCMS provides a concise and powerful filter function, which can easily realize the continuous conversion from string to floating-point number to integer.## Conversion from string to floating-point number First

2025-11-08

What does the `integer` filter default to return when a numeric string cannot be converted to an integer?

In AnQiCMS template development and content operation, we often need to format and convert the data displayed on the page.The filter is an indispensable tool to achieve this goal. Among them, the `integer` filter plays an important role in processing numeric data due to its practical function of converting string values of numeric types into integers.However, when faced with uncertain data sources, a common issue is: what does the `integer` filter default to return when a numeric string cannot be successfully converted to an integer?When building a website using AnQiCMS

2025-11-08

How does AnQiCMS convert user input numeric text to integer type?

In website content management, we often encounter situations where we need to handle digital information, such as product inventory quantities, article reading volumes, and ages submitted by users, etc.These numbers may exist in text form during back-end entry, but when it comes to actual calculations, sorting, or display, we need to ensure that they are true numeric types, not mere text strings.AnQiCMS as a rich-featured enterprise-level content management system, fully considering this point, has provided us with a flexible solution to deal with the need for this kind of data type conversion.###

2025-11-08

What value will the `float` filter return when encountering a non-numeric string?

In AnQi CMS template development, filters are an important tool for processing and formatting data.They can help us present the data passed from the backend in a way that is more in line with the front-end display requirements.Among them, the `float` filter is specifically used to convert numbers to floating-point format.However, when it encounters a non-numeric string, its behavior becomes particularly critical because it directly affects the accuracy of the template output and the stability of the program.The core function of the `float` filter is to convert the input value to a floating-point number type

2025-11-08

How does the `floatformat` filter keep a floating-point number to two decimal places?

In AnQi CMS, the flexibility and accuracy of content display are one of the features that users highly value.When dealing with content related to numbers, especially when it involves amounts, percentages, or other data that requires precise display, the formatting of floating-point numbers is particularly important.An unprocessed floating-point number, such as `34.23234` or `12.00000`, may appear disorganized on the front-end page and affect user experience and the professionalism of the information.Fortunately, AnQi CMS is built-in with a powerful template engine, which draws on the essence of Django template syntax

2025-11-08

I want to display floating-point numbers without extra zeros, can the `floatformat` filter do that?

In AnQi CMS templates, handling the display of floating-point numbers, especially the need to remove unnecessary zeros at the end of the numbers, is a practical demand that many website operators encounter.When our product price is `12.5000` or a certain statistical number is `34.00`, these extra zeros are not only unattractive but may also confuse visitors.At this point, the `floatformat` filter built into Anqi CMS can come into play.How does the `floatformat` filter prevent extra zeros from displaying in floating-point numbers?

2025-11-08

How to force the `floatformat` filter to display a certain number of decimal places (such as 3), even if the end is zero?

In website content management, especially when it involves prices, statistics, or any scenario where it is necessary to display numbers accurately, we often need to ensure that the decimal places of the numbers are consistent.The `floatformat` filter provided by AnQi CMS is a very practical tool that helps us format floating-point numbers.However, sometimes its default behavior may be confusing, especially when the trailing zeros may quietly 'disappear', which poses a challenge for the unified display of data.Imagine you have a product priced at `12.50` yuan

2025-11-08

How will the `floatformat` filter handle non-numeric input?

During the template creation process in AnQi CMS, the `floatformat` filter is a commonly used tool for handling number display, especially for floating-point number formatting.It can help us accurately control the decimal places of numbers on the page, making the data display more neat and professional.However, when the `floatformat` filter receives non-numeric input, its handling may confuse some users.Understanding this mechanism is crucial to avoiding potential display issues with page data.The main function of the `floatformat` filter is to use the parameters we specify

2025-11-08