How do I calculate the sum of two product prices in a template and ensure the result is an accurate floating-point number?

Calendar 👁️ 77

In the operation of e-commerce websites, the calculation and display of product prices are often one of the core links.AnQi CMS is an efficient content management system, although it mainly focuses on content management and presentation, its powerful template engine also supports us in performing some basic arithmetic operations, such as calculating the total sum of prices for two or more products, and ensuring that the final result is presented in the form of an accurate floating-point number.

This article will discuss in detail how to implement this requirement in the Anqi CMS template, covering how to obtain product prices, perform addition operations, and how to control floating-point precision.

Get product price information

Firstly, we need to obtain the price from the product document. In the Anqi CMS template system, we usually usearchiveDetailTag to get detailed information of a single document, including the price of the product(Price) field.

Assuming that the document IDs corresponding to your two products are101and102. You can obtain their prices in the template in the following way:

{# 获取产品A(ID为101)的价格 #}
{% archiveDetail productA_price_raw with name="Price" id="101" %}
{# 获取产品B(ID为102)的价格 #}
{% archiveDetail productB_price_raw with name="Price" id="102" %}

here,productA_price_rawandproductB_price_rawThe original price data of two products will be stored separately. It is worth noting that,PriceThe field is usually recognized as a numeric type when entered in the background, but to ensure the accuracy of subsequent calculations in the template, it is best to explicitly convert it to a floating-point number type. This can be done by|floatFilter implementation.

{# 确保获取到的价格是浮点数类型,以便后续精确计算 #}
{% set price_a = productA_price_raw|float %}
{% set price_b = productB_price_raw|float %}

{% set ... %}Tags are used to define a variable and assign it in a template, which is very useful for storing intermediate calculation results.

Perform the summation operation of product prices.

The Anqi CMS template engine supports basic arithmetic operations. Once you store the product price in a variable and ensure it is of floating-point type, you can use+The operator performs a simple addition.

{# 计算两个产品价格的总和 #}
{% set total_sum = price_a + price_b %}

at this point,total_sumThe variable will holdprice_aandprice_bThe result of the floating-point number after addition.

Ensure floating-point precision and formatted output.

In computer science, floating-point arithmetic can sometimes produce tiny precision errors due to its internal binary representation (for example0.1 + 0.2May not be exactly equal to0.3Although for most display scenarios, this error can be ignored, in sensitive scenarios involving money, we usually need to format the result to a specific number of decimal places (such as two) and round it to achieve a visual 'accuracy' effect.

The Anqi CMS template provides two powerful filters to help us format floating-point numbers:

  1. floatformatFilterThe filter is used to format floating-point numbers to a specified number of decimal places.By default, it will be formatted to one decimal place and omit the trailing zeros.By passing a numeric parameter, you can specify the number of decimal places to be retained. For example,|floatformat:2means retaining two decimal places.

    <p>产品总和(使用floatformat):<span style="color:red; font-weight:bold;">{{ total_sum|floatformat:2 }}</span> 元</p>
    
  2. stringformatFilterThis filter provides more flexible formatting capabilities, similar to the function in Go language.fmt.Sprintf()You can use%fformat specifiers to format floating-point numbers, and then proceed to%.2fSpecify to keep two decimal places.

    <p>产品总和(使用stringformat):<span style="color:green; font-weight:bold;">{{ total_sum|stringformat:"%.2f" }}</span> 元</p>
    

    Both methods can effectively control the display accuracy of floating-point number results, so that the total appears in the exact two decimal places we expect.

Complete operation example

Integrate the above steps and here is a complete code example that shows how to calculate the total sum of two product prices and display it accurately in the Anqi CMS template:

{# 假设有两个产品,ID分别为101和102 #}

{# 1. 获取产品A(ID为101)的原始价格 #}
{% archiveDetail productA_price_raw with name="Price" id="101" %}
{# 2. 获取产品B(ID为102)的原始价格 #}
{% archiveDetail productB_price_raw with name="Price" id="102" %}

{# 3. 确保获取到的价格是浮点数类型,并赋给新变量以便后续计算 #}
{# 假设产品A价格为 99.99,产品B价格为 149.50 #}
{% set price_a = productA_price_raw|float %}
{% set price_b = productB_price_raw|float %}

{# 4. 进行价格求和运算 #}
{% set total_sum = price_a + price_b %}

{# 5. 使用 floatformat 过滤器将总和格式化为两位小数 #}
<p>产品总和(使用floatformat):<span style="color:red; font-weight:bold;">{{ total_sum|floatformat:2 }}</span> 元</p>

{# 6. 也可以使用 stringformat 过滤器进行更精细的格式化 #}
<p>产品总和(使用stringformat):<span style="color:green; font-weight:bold;">{{ total_sum|stringformat:"%.2f" }}</span> 元</p>

{# 如果需要显示原始价格,也可以进行格式化 #}
<p>产品A价格: {{ price_a|floatformat:2 }} 元</p>
<p>产品B价格: {{ price_b|floatformat:2 }} 元</p>

By following these steps, you will be able to achieve precise summation and formatted display of product prices in the Anqi CMS template.

Frequently Asked Questions (FAQ)

Q1: Why do simple floating-point additions sometimes result in something similar?0.1 + 0.2 = 0.30000000000000004What is the result?

Floating-point numbers are stored in binary form inside computers, which leads to some decimal fractions (such as 0.1, 0.2) being unable to be represented precisely, thus causing slight errors in calculations.The Go language used by AnQi CMS at the bottom layer also follows this general principle in floating-point arithmetic.Therefore, when performing floating-point addition and subtraction directly in the template, if an accurate decimal result is required, the most reliable way is to complete it on the backend (data layer)

Related articles

How can a number conversion filter be used to process numeric (string) values submitted by a front-end form?

In website operation, we often encounter situations where users need to enter numerical values in front-end forms, such as product quantity, price range, and user age, etc.However, these data obtained from the form, even though they look like numbers, are often treated as string types by the Web system.This brings inconvenience to subsequent calculations, comparisons, and presentations, which may lead to type errors or inaccurate calculation results.AnQiCMS (AnQiCMS) leverages its powerful functionality based on the Django template engine to provide a series of concise and efficient filters (filters)

2025-11-08

How can a template determine whether a variable is a valid number (integer or floating-point), so that it can perform subsequent operations?

In Anqi CMS template development, we often need to handle various types of data.In which, determining whether a variable is a valid number (whether an integer or a floating-point number), in order to perform corresponding mathematical operations or display logic, is a common requirement.Although the Anqi CMS template engine (based on Django template syntax) does not provide a direct `is_numeric` function, we can cleverly use its built-in filters and logical judgment tags to achieve this goal.The AnQi CMS template language is designed simply and efficiently, variables are usually through double curly braces

2025-11-08

How to convert a floating-point number in a template to an integer and then perform logical comparison with other integers?

During the process of website operation and content management, we often need to perform fine control and logical judgment on the displayed data.Especially at the template level, data type conversion is a common requirement.For example, when a certain value stored in your content management system (such as product prices, stock quantities, etc.) is of floating-point type, but you may want to treat it as an integer when performing logical comparisons in the template.AnQiCMS (AnQiCMS) with its powerful template engine similar to Django provides a direct and efficient solution for such scenarios

2025-11-08

How does the `get_digit` filter perform on Chinese string input?

During the template development process of AnQiCMS, we often use various filters to process and format data.The `get_digit` filter is one of them, its main function is to extract the specified digit from a number.However, when we pass Chinese string as input to the `get_digit` filter, its behavior may be different from what we intuitively expect.### `get_digit` filter's basic function First, let's review the `get_digit`

2025-11-08

How to ensure consistent display format when the `floatformat` filter handles 0 values?

In Anqi CMS template development, the `floatformat` filter is undoubtedly an important tool for handling floating-point number display, which can help us standardize the display of numbers on the page.However, when encountering zero values or decimal points followed by all zeros, the default behavior may lead to inconsistent display formats, which is particularly prominent in scenarios requiring strict uniformity (such as financial data, product prices).### The basic usage of `floatformat` filter First, let's review the basic function of the `floatformat` filter

2025-11-08

How to convert a user's input currency string (such as "123.45") to a numeric type in a template?

When building websites on AnQiCMS, we often encounter scenarios where we need to handle data type conversions, especially when data from the backend is stored as strings but needs to be performed numerical calculations or comparisons on the frontend.For example, product prices, quantities, and other information, although they may be entered in the background as strings such as '123.45', in the template, we may need to treat them as numbers for arithmetic operations such as addition, subtraction, multiplication, or make conditional judgments based on the magnitude of the values.Luckyly, AnQiCMS's powerful template engine provides simple and efficient filters (filters)

2025-11-08

How `get_digit` filter extracts the year part from a longer number?

In daily website content operation, we often encounter the need to extract specific information from data, such as extracting the year from a long number.AnQi CMS provides rich template filters and tags to help us flexibly handle these data.Today, let's talk about the `get_digit` filter and discuss its application in the specific scenario of extracting the year, as well as other methods that are more suitable for extracting the year.First, let's understand what the `get_digit` filter is used for.This filter is designed very cleverly

2025-11-08

How to implement dynamic adjustment of the output format of calculation results in a template, for example, displaying different currency formats based on countries or regions?

In website operation, especially when facing global users, the localization experience of content is crucial.Among them, dynamically adjusting the output format of the calculated results, such as displaying different currency formats based on the user's country or region, is a common requirement.AnQiCMS (AnQiCMS) is a flexible content management system that provides a powerful template engine and rich tags/filters, allowing us to elegantly implement this feature.To achieve this goal, we mainly rely on the several core capabilities of the Anqie CMS template engine: **Retrieve the current site or user's language/region information**

2025-11-08