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

Calendar 👁️ 62

In website content operation, the precise display of numbers is often crucial, whether it is product prices, statistical data, or technical indicators, the display accuracy of decimal points directly affects the accuracy of information and the understanding of users.AnQiCMS provides a flexible template engine, allowing us to easily adjust the decimal precision of numbers in front-end templates, thereby meeting various complex display requirements.

The AnqiCMS template system is developed based on Go language, with a syntax style similar to Django, and it provides great convenience for us to handle data display through its powerful Filter function. When we need to control the decimal point accuracy of numbers, we mainly usefloatformatandstringformatThese two filters.

Precise control:floatformatFilter

floatformatThe filter is a convenient tool specifically designed for floating-point numbers (decimals), which can help us quickly adjust the number of decimal places displayed.This filter intelligently handles the rounding of numbers and automatically removes trailing zeros as needed, making the display more concise.

Basic Usage One: Auto-Optimize DisplayIf We Do NotfloatformatThe filter specifies any parameter, it will automatically keep one decimal place for floating-point numbers, and if the decimal part ends in zero, it will directly remove the decimal part and display it as an integer. For example,34.23234It will be displayed as34.2while34.00000It will be displayed as34.

{# 假设 item.Price 的值为 34.23234 #}
<p>商品价格:{{ item.Price|floatformat }}</p> {# 输出: 34.2 #}

{# 假设 item.DiscountRate 的值为 34.00000 #}
<p>折扣比例:{{ item.DiscountRate|floatformat }}</p> {# 输出: 34 #}

{# 假设 item.TaxRate 的值为 34.26000 #}
<p>税率:{{ item.TaxRate|floatformat }}</p> {# 输出: 34.3 #}

Basic usage two: Specify the number of decimal placesIf we need to control the number of decimal places accurately, we can add tofloatformatThe filter passes a numeric parameter. This number represents the number of decimal places to retain. For example,floatformat:3It means retaining three decimal places. It also rounds off accordingly.

{# 假设 item.Price 的值为 34.23234 #}
<p>商品价格:{{ item.Price|floatformat:3 }}</p> {# 输出: 34.232 #}

{# 假设 item.DiscountRate 的值为 34.00000 #}
<p>折扣比例:{{ item.DiscountRate|floatformat:3 }}</p> {# 输出: 34.000 #}

{# 假设 item.TaxRate 的值为 34.26000 #}
<p>税率:{{ item.TaxRate|floatformat:3 }}</p> {# 输出: 34.260 #}

It is noteworthy that when the number of decimal places is specified as zero, such asfloatformat:0it will be displayed directly as an integer and rounded. For example39.56000|floatformat:0It will display40.

Dynamically adjust the number of decimal places floatformatThe filter also supports dynamic parameter passing, which means we can adjust the number of decimal places based on different contexts or configurations.For example, you can set a global decimal place in the background and then pass it to the filter through a variable.

{# 假设在某个地方我们定义了 decimalPlaces = 2 #}
{% set decimalPlaces = 2 %}
<p>动态价格:{{ item.Price|floatformat:decimalPlaces }}</p> {# 输出: 34.23 #}

Advanced customization:stringformatFilter

exceptfloatformatother than,stringformatThe filter provides more general string formatting capabilities, similar to those in programming languages.printfA function that controls output through string formatting. It is also applicable for floating-point precision control, and it can provide more fine-grained control, such as forcing the display of a certain number of decimal places, even if the trailing zeros.

Use%.xfControl the precision of floating-point numbers.By%.xfSuch a formatting string, we can specify the number of decimal places to be retained for floating-point numbers. In whichxThat is the number of digits you want to retain.

{# 假设 item.Price 的值为 3.141592653 #}
<p>商品价格(精确到两位):{{ item.Price|stringformat:"%.2f" }}</p> {# 输出: 3.14 #}

{# 假设 item.DiscountRate 的值为 34.00000 #}
<p>折扣比例(强制三位小数):{{ item.DiscountRate|stringformat:"%.3f" }}</p> {# 输出: 34.000 #}

{# 假设 item.TaxRate 的值为 34.26000 #}
<p>税率(精确到零位小数):{{ item.TaxRate|stringformat:"%.0f" }}</p> {# 输出: 34 #}

withfloatformatdifferent,stringformatWhen specified to a certain precision, it will strictly display the format string, including the zeros at the end. For example,34.00000|stringformat:"%.3f"It will still output34.000instead of34This is very useful in some scenarios where alignment or unified display format is required.

How to choose the appropriate filter?

ChoosefloatformatandstringformatAs needed, you can decide:

  • Selectfloatformat: If you need a concise floating-point display, allow automatic removal of trailing zeros and standard rounding.It focuses more on the display optimization of floating-point numbers, the default behavior usually meets most scenarios.
  • SelectstringformatIf you need more fine-grained control, such as forcing the display of a fixed number of decimal places (even if zero), or embedding numbers into more complex string formats.Its flexibility is higher, but it requires a certain understanding of format strings.

In practical application, for example, when displaying product details such as price, we can use it like this:

{# 从文档详情中获取产品的价格,并保留两位小数 #}
{% archiveDetail productPrice with name="Price" %}
<p>产品售价:¥{{ productPrice|floatformat:2 }}</p>

{# 或者,如果需要强制显示两位小数 #}
<p>产品售价(严格格式):¥{{ productPrice|stringformat:"%.2f" }}</p>

By flexibly using these filters, we can freely control the display accuracy of numbers in the AnQiCMS template, presenting more professional and readable content to users.


Frequently Asked Questions (FAQ)

  1. Can I dynamically adjust the display accuracy based on different user permissions or page types?Of course you can. You can pass the decimal precision as a variable to the filter. For example, set a variable nameddecimal_precisionin the background or through programming logic, and then use it in the template.{{ some_value|floatformat:decimal_precision }}or{{ some_value|stringformat:"%." ~ decimal_precision ~ "f" }}. So, different users or pages can see the values displayed with different precision.

  2. If my data is not of the floating-point number type, can I use it directly?floatformatorstringformatWill it cause an error? floatformatThe filter usually expects to receive floating-point numbers. If your data is an integer, it usually works fine.If your data is a string (for example, “123.45”) when usingfloatformatorstringformatBefore that, it's best to go throughfloatThe filter converts it to a floating-point number, for example{{ "123.45"|float|floatformat:2 }}This avoids potential type conversion errors.

  3. floatformatandstringformatWhen adjusting precision, should it be rounded or truncated directly?These two filters follow the standard rounding rules. For example, if you format12.345as two decimal places, it will display as12.35; if you format12.344as two decimal places, it will display as12.34They will not be truncated directly, but will be judged according to the next digit.

Related articles

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?

In website operation, we often encounter the need to handle numerical data such as product prices or service charges.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 on these prices in a template (such as the order total), directly performing a 'sum' operation on the string will yield unexpected results (such as '199.5015.00' instead of '214.50').At this point, it is necessary to convert these string prices into actual numbers

2025-11-08

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

How does the Anqi CMS template handle numeric data that may be received as strings from external APIs?

In website operation, we often encounter situations where we need to integrate data from different external APIs.These APIs provide data of various types and formats, and they are quite different, especially when dealing with numerical data. We may find that fields such as "price", "stock", or "rating", which should be numeric, are returned as strings.This not only brings trouble to the template display, it may also affect data calculation and subsequent processing.AnQi CMS, with its flexible template engine and rich data processing capabilities, provides us with an elegant solution

2025-11-08