How to precisely control the decimal places of floating-point numbers using the `floatformat` filter in Anqi CMS, and how to implement rounding or specific rounding rules?

Calendar 👁️ 64

In a content management system, clear presentation and precise control of data is crucial, especially when displaying amounts, percentages, or any floating-point numbers. AnQiCMS provides a powerful template engine, wherefloatformatThe filter is a tool to handle such floating-point number display issues.It can help us flexibly control the number of decimal places and implement different rounding rules according to the needs, making the digital data on the website both beautiful and accurate.

Core function analysis:floatformatFilter Overview

floatformatIt is a very practical filter in Anqi CMS template, mainly used to format floating-point numbers to control the number of decimal places displayed. Whether you want to display product prices, statistical percentages, or any other numbers with decimals,floatformatCan all present data in a unified, professional format in front of users.

Its basic usage is very simple, through the pipeline symbol|The variable to be processed is passed tofloatformatFilter, and optionally provide a parameter to specify the number of decimal places.

{{ 您的数值 | floatformat: 小数位数 }}

Fine-grained control: specifying the number of decimal places and default behavior.

floatformatThe filter shows flexible and diverse behavior when processing floating-point numbers, which mainly depends on whether you provide parameters and the specific values of the parameters.

first, When used without any parametersfloatformathourThe filter will intelligently attempt to keep decimal numbers to one decimal place.However, if the decimal part of the calculation is exactly zero (for example, 34.000), it will omit the decimal point and display as an integer (such as 34).When executing this default operation,floatformatAdheres to the standard rounding rules.

  • For example:{{ 34.23234 | floatformat }}The result is34.2
  • For example:{{ 34.00000 | floatformat }}The result is34
  • For example:{{ 34.26000 | floatformat }}The result is34.3

secondly,When you provide a positive integer argument.,floatformatForces the floating-point number to be formatted to the specified number of decimal places. Even if the decimal places of the original number are insufficient, it will fill zeros to reach the required number of places.If the decimal places of the original number exceed, it will be truncated according to the rounding rule.

  • For example:{{ 34.23234 | floatformat:3 }}The result is34.232
  • For example:{{ 34.00000 | floatformat:3 }}The result is34.000

In-depth exploration: Rounding and significant decimal places.

floatformatThe strength of the filter also lies in its ability to handle more complex rounding requirements.

When the parameter is0hour,floatformatThe number will be rounded to the nearest integer. It will strictly follow the standard rounding rules and display the integer without any decimal points.This is very useful for scenarios where you need to display integer values in reports or summaries while also maintaining a certain rounding accuracy.

  • For example:{{ 39.56000 | floatformat:"0" }}The result is40(Round off)
  • For example:{{ 34.23234 | floatformat:"0" }}The result is34

When the parameter is a negative integer,floatformatProvided a unique way to control the 'number of significant digits'. For example,floatformat:"-N"will retainNAt the same time, it intelligently removes trailing zeros. This means it focuses more on the actual numerical representation of floating-point numbers, avoiding unnecessary zero padding to make the numbers look simpler.

  • For example:{{ 34.23234 | floatformat:"-3" }}The result is34.232
  • For example:{{ 34.00000 | floatformat:"-3" }}The result is34
  • For example:{{ 34.26000 | floatformat:"-3" }}The result is34.26

The main difference in the usage of this negative integer parameter is that positive integer parameters willalwayspad with zeros to reach the specified number of digits, while negative integer parameters will be within the specified number of digitsremoveExcessive trailing zeros.

Example of application scenario: Make data display more professional.

UnderstoodfloatformatAfter using the various usages, we can apply it in various scenarios to make the data display more in line with expectations and user habits:

  1. Product price display:On e-commerce websites, prices are usually precise to two decimal places.
    
    <p>商品价格: ¥ {{ product.Price | floatformat:2 }}</p>
    
  2. Percentage calculation and display:On the statistics or analysis page, convert the ratio to a percentage and retain an appropriate number of decimal places.
    
    {% set rate = 0.12345 %}
    <p>转化率: {{ (rate * 100) | floatformat:2 }}%</p> {# 结果是 12.35% #}
    
  3. Financial statement data:When you need to round a large floating-point number to an integer for a quick overview.
    
    <p>总销售额(约): {{ total_sales | floatformat:0 }} 元</p>
    
  4. Scientific or engineering data:Need to display significant digits while avoiding too many unnecessary zeros.
    
    <p>测量值: {{ sensor_data | floatformat:"-4" }} 单位</p>
    

Points to note

While usingfloatformatA few points to note when using the filter:

  • Data type: floatformatUsed to handle numeric types or strings that can be parsed as numbers.If a non-numeric value is passed, it usually will not cause the template rendering to break, but the result may not be what you expect. *

Related articles

How to use `integer` and `float` filters to convert string numbers in Anqi CMS templates to numeric types that can be used in mathematical operations?

During the development of Anqi CMS templates, we often encounter scenarios where we need to perform numerical operations, such as calculating the total price of goods, comparing inventory quantities, or displaying different content based on specific values.However, sometimes the data obtained from the background, even if it looks like a number, may exist in the template as a string, which prevents us from performing mathematical operations directly.

2025-11-08

How to automatically add line numbers to code blocks or list content in `linenumbers` filter in Anqie CMS to enhance readability?

In daily content creation and website operations, we often need to insert code examples, configuration lists, or detailed operation steps in articles.The characteristic of this content is that it is multi-line text, and if line numbers can be automatically added to it, it will greatly enhance the reader's reading experience and the professionalism of the content.Imagine when you need to explain a part of the code to the reader, or guide them to complete a complex setup, you can accurately mention 'See line 5 of the code' or 'In step 3', this improvement in communication efficiency is self-evident.

2025-11-08

How to use the `linebreaks` and `linebreaksbr` filters to convert newline characters in the plain text content entered by an Anqie CMS user into HTML `<p>` or `<br>` tags?

In a content management system, processing plain text content entered by users and displaying it on the web page in the expected format is a common requirement.When the user enters text with line breaks in the back-end editor, the browser does not default to rendering it as HTML line breaks.All content may be squeezed onto one line, causing disordered layout and affecting reading experience.Fortunately, AnQiCMS provides a convenient template filter to solve this problem.

2025-11-08

What are the application scenarios and encoding differences of the `urlencode` and `iriencode` filters in the AnQi CMS template when encoding URL parameters?

In AnQiCMS template development, when handling URL parameters, we often encounter the need to encode them.This is mainly to ensure the legality of the URL, avoid special characters from destroying the URL structure, and correctly transmit data containing non-ASCII characters (such as Chinese).AnQiCMS provides the `urlencode` and `iriencode` filters to help us complete this task, but their application scenarios and encoding differences are not the same.

2025-11-08

How to use the `join` filter to concatenate the multiple tags (array) of an Anqi CMS article into a comma-separated string output?

AnQiCMS (AnQiCMS) is loved by website operators for its flexible and efficient features.In daily content management, articles or products often associate with multiple tags (Tag), which are stored in the system in the form of an array.When we need to display these tags on the front-end page, for example, showing

2025-11-08

How to use the `split` filter to convert the custom delimiter string returned by the Anqie CMS backend (such as "keyword1|keyword2") into an array for easy traversal?

In AnQi CMS content management practice, flexibility is the key to improving efficiency and achieving personalized display.Sometimes, we may encounter such a requirement: the backend returns a string of text separated by a special symbol through a custom field, such as a product introduction may have multiple related keywords, and it is stored as 'keyword1|keyword2|keyword3' such a format.How can I beautifully split this string of text into individual keywords and make them convenient for display or iteration in a front-end template?

2025-11-08

How to split a normal string into an array of individual characters using the `make_list` filter in the Anqi CMS template for more refined text processing?

In the world of AnQi CMS templates, we often need to process content in various ways, sometimes by paragraphs, sometimes by sentences, and sometimes, we need to refine the text more finely, down to every character.When conventional string processing methods fail to meet such refined needs, the `make_list` filter can excel, as it can split a common string into an array of individual characters, providing unprecedented flexibility for template designers.

2025-11-08

How to center, left-align, and right-align Chinese string with specified width using `center`, `ljust`, and `rjust` filters in the Anqi CMS template?

When building and maintaining website content, we often need to pay attention to the visual presentation of information, especially the alignment of text content.It is particularly important to accurately control the centering, left alignment, or right alignment of strings, whether it is for the neatness and beauty of the table or to maintain visual balance within a fixed width area.AnQiCMS with its flexible and powerful template engine, provides us with several very practical filters to easily achieve this goal, even for strings containing Chinese characters.

2025-11-08