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

Calendar 👁️ 55

When building a website with AnQiCMS, we often encounter scenarios where we need to handle data type conversions, especially when data from the backend is stored as a string but needs to be performed numerical calculations or comparisons on the frontend.For example, product price, quantity information, although it may be entered as a string such as "123.45" in the background, but in the template, we may need to treat it as a number for addition, subtraction, multiplication, or conditional judgment based on the size of the value.Fortunately, AnQiCMS's powerful template engine provides convenient and efficient filters (filters), which can easily achieve this kind of data conversion, making your content operation and display more flexible.

Why do you need to convert currency strings to numeric types?

Why do we need to perform this transformation? Imagine that you are displaying a shopping cart page, where both the product price and quantity are strings.If you want to calculate the total price of goods or display different promotional information based on price ranges, you cannot do so directly.After converting these strings to numeric types, you can:

  • Perform mathematical operations:Easily perform addition, subtraction, multiplication, division, and other calculations.
  • Perform numerical comparison:For example, check if the price is higher than a certain threshold.
  • Precise formatting:Although the numeric display can be used with other filters, the underlying is numeric type, which can ensure the accuracy of formatting.

The solution in AnQiCMS template:floatandintegerFilter

AnQiCMS template engine is based on Django template syntax, one of its core advantages is the rich filter functions. For converting strings to numeric types, we mainly use two very practical filters:floatandinteger.

  • floatFilter:Used to convert a string to a floating-point number (i.e., a number with a decimal point). This is the most common choice for processing monetary amounts, as money often contains decimal parts.

    • Usage:{{ 您的字符串变量 | float }}
    • For example:{{ "123.45" | float }}will output123.45
    • If the conversion fails (for example, if the string is "abc"), it will return by default0.0.
  • integerFilter:Used to convert a string to an integer (i.e., a number without a decimal point).If your data does not require decimal parts or needs to be converted for integer operations, this filter is very useful.

    • Usage:{{ 您的字符串变量 | integer }}
    • For example:{{ "123" | integer }}will output123
    • If the conversion fails, it will return by default0.

Actual application scenarios and examples

After understanding the basic usage of these two filters, let's look at some specific application scenarios:

Scenario one: Convert product prices to numbers

Assuming there is one in your content modelPriceThe field stores the price in string format, such as{{ archive.Price }}. To convert it to a floating-point number in the template, just applyfloatFilter:

<div>商品价格:{{ archive.Price | float }} 元</div>

Scenario two: Calculate the total price of goods

If you need to calculate the quantity of a productQuantitywith the pricePriceof the product, remember that each string variable involved in the calculation needs to be converted to a numeric type:

{% set totalPrice = archive.Price | float * archive.Quantity | float %}
<div>总价:{{ totalPrice }} 元</div>

We used heresettag to define a temporary variabletotalPriceStore the calculation result for later use. You can also perform calculations directly in the expression.

Scenario 3: Conditional judgment based on numbers.

Do you want to judge the discount activities based on product prices? After converting to a number, the conditional judgment becomes effortless:

{% if archive.Price | float > 100.00 %}
    <div>此商品享受满百减免优惠!</div>
{% else %}
    <div>再买一点就能享受优惠啦!</div>
{% endif %}

Scenario four: Displaying the number after formatting

AlthoughfloatThe filter converts a string to a number, but sometimes we also need to control the display format of the number, such as retaining two decimal places. At this point, we can combinefloatformatTo implement a filter. It takes a numeric parameter specifying the number of decimal places to retain.

<div>格式化后的价格:{{ archive.Price | float | floatformat:2 }} 元</div>

Please note,floatformatIt is based on the numeric type for formatting,

Related articles

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 do I calculate the sum of two product prices in a template and ensure the result is an accurate floating-point number?

In the operation of e-commerce websites, the calculation and display of product prices are often one of the core links.AnQi CMS as an efficient content management system, although it mainly focuses on content management and presentation, its powerful template engine also supports us to perform some basic arithmetic operations, such as calculating the total price of two or more products, and ensuring that the final result is presented in an accurate floating-point form.This article will discuss in detail how to implement this requirement in Anqi CMS templates, covering how to obtain product prices, perform addition operations, and how to control floating-point precision.###

2025-11-08

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 `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

How does the `stringformat` filter convert a floating-point number to a string with thousand separators?

In Anqi CMS template development, the `stringformat` filter is a very practical tool that allows us to flexibly format various data types, especially numbers and strings, to meet the needs of page display.When dealing with floating-point numbers, we often encounter the need to convert them to strings in a specific format, such as retaining decimal places.However, if large numbers are formatted with thousands separators (e.g., 1,234,567.89), it can significantly enhance the readability of the numbers and make the data presentation more professional.So, in AnQi CMS

2025-11-08

How to convert a numeric field in a template to a string without affecting other logic?

In AnQiCMS template development, we often encounter scenarios where it is necessary to display numeric data combined with text content.For example, you may need to add the product ID at the end of a product title, or add “times read” after the number of reads in an article.How to flexibly convert numeric fields in templates to strings and concatenate them without affecting other logical judgments or calculations?It's lucky that

2025-11-08