How to format numbers in AnQiCMS templates, such as retaining decimal places?

Calendar 👁️ 65

In AnQiCMS template development, formatting numbers for display, especially controlling decimal places, is a very common requirement.Whether you want to display the price of goods, the percentage in statistical data, or other numbers that need to be presented accurately, AnQiCMS's powerful template engine provides flexible filters to help you achieve these goals.

AnQiCMS template syntax is similar to Django, variables are usually output through double curly braces{{ 变量 }}and filters are output through the pipe symbol|Applied after the variable. Below, we will discuss in detail how to format numbers in the AnQiCMS template, especially retaining decimal places.

UsefloatformatFilter retains decimal places

When we need to control numbers, especially decimal numbers, accurately,floatformatThe filter is the preferred tool. This filter is specifically used for formatting floating-point numbers and provides various ways to retain decimal places.

The basic usage is{{ 变量|floatformat:参数 }}. Among them,参数It can be an integer used to specify the number of decimal places you want to keep.

  1. The default behavior (keep one decimal place, do not display trailing zeros)If no parameters are specified,floatformatThe default is to try to keep one decimal place. If the number itself is an integer, the decimal part will not be displayed; if the decimal part is only one digit and zero, it will also be omitted. For example,{{ 34.23234|floatformat }}It will display34.2while{{ 34.00000|floatformat }}it will display:34.

  2. Keep the specified number of decimal places (positive integer parameter)When you need to control the number of decimal places accurately, you can pass a positive integer as a parameter. For example, to keep three decimal places, you can use{{ 34.23234|floatformat:3 }}It will display34.232. Even if the decimal places are insufficient, it will be filled with zeros, such as{{ 34.00000|floatformat:3 }}Will be displayed34.000.

  3. Rounded to an integer (parameter is0or an empty string"")If you want to round a floating-point number to the nearest integer, you can pass0Or an empty string as a parameter. For example,{{ 39.56000|floatformat:"0" }}Will be displayed40.

  4. Negative integer parameters are calculated from right to left to determine the number of decimal places. floatformatNegative integer parameters are also supported, but this is less commonly used when retaining decimal places. It rounds from the end of the number. For example,{{ 34.23234|floatformat:"-3" }}It will still be displayed34.232Because it retains 3 decimal places, counting from the end, it just reaches the third place.

Through these flexible parameters,floatformatThe filter can meet the vast majority of needs for retaining decimal places.

UsestringformatFilter for more general number formatting

If your formatting requirements are more complex, or you are accustomed to formatting strings similar to the C language, thenstringformatThe filter will surprise you. It can format numbers, strings, and any value according to the format string you define.

Regarding retaining decimal places,stringformatusually combined%.nfThis format symbol is used, among whichnrepresents the number of decimal places you want to keep. For example, to keep two decimal places, you can use{{ 变量|stringformat:"%.2f" }}. If your variableitem.PriceThe value is3.141592653then{{ item.Price|stringformat:"%.2f" }}Will be displayed3.14.

stringformatThe strength lies in its versatility, it is not limited to floating-point numbers, but can also be used for integers (%d), strings (%s)and other complex formatting requirements, such as adding specific text or symbols before and after numbers. For example,{{ 888|stringformat:"Test: %d" }}It will displayTest: 888.

Auxiliary filter:integerandfloatEnsure data type

In some cases, the data you receive from the backend may not be strictly numeric types, such as prices or quantities stored as strings.Before formatting these values, it is best to convert them to actual numeric types to avoid potential errors or unexpected behavior.

integerA filter can convert a value to an integer. If the conversion fails, it will return0. For example,{{ "5.4"|float|integer }}Will be displayed5.

floatA filter can also convert a value to a floating-point number. If the conversion fails, it will return0.0. For example,{{ "foobar"|float }}Will be displayed0.000000.

In applicationfloatformatorstringformatBefore, use firstfloatThe filter ensures that you are processing a floating-point number, thereby ensuring the accuracy of the formatted results.

Summary

AnQiCMS template engine throughfloatformatandstringformatThese powerful filters provide flexible and precise control for the formatting display of numbers, especially for retaining decimal places.floatformatSimple and intuitive, suitable for directly controlling the number of decimal places; andstringformatIt provides C language style formatting capabilities, suitable for more complex output needs. CombinedintegerandfloatA helper filter that ensures proper data processing and perfect presentation, thereby greatly enhancing the professionalism and user experience of the AnQiCMS website.


Frequently Asked Questions (FAQ)

Q1: How can I add a currency symbol before or after a number?

A1: You can directly concatenate the currency symbol with the formatted number in the template. For example, ifitem.PriceIs the product price, and you want to keep two decimal places and display the Chinese Yuan symbol:{{ '¥' }}{{ item.Price|floatformat:2 }}Or use:stringformatMore concise:{{ item.Price|stringformat:"¥%.2f" }}.

Q2: Besides retaining decimal places, what other formatting operations can AnQiCMS templates perform on numbers?

A2: AnQiCMS template supports various number formatting operations. In addition tostringformatImplement various C language style formatting (such as zero-padding, specifying width, etc.), you can also useaddfilters to add numbers, ordivisiblebyFilter to determine if a number can be evenly divided by another number, etc. For more detailed number-related filters, you can refer totag-calc.mdandfilter-*.mda series of documents.

Q3: How to determine if a variable is a valid numeric type in a template?

A3: You can useintegerorfloatThe filter tries to convert the variable to a number and then make a judgment based on the conversion result. For example, ifsomeValueThis should be a number, but it may be text or null:{% set num_value = someValue|float %} {% if num_value != 0 or someValue == '0' %} <!-- 这是一个有效的数字(或者原始字符串就是'0') --> {% else %} <!-- 不是有效数字 --> {% endif %}This method can help you validate the data type before displaying, ensuring that the page will not crash due to invalid data.

Related articles

How to implement custom template file calling for category or article detail pages in AnQiCMS?

During the process of building a website with AnQiCMS, we often encounter such needs: we hope that a certain category list page or a unique article detail page has a layout and style that is different from the global unified default template.AnQiCMS is a content management system focused on flexibility and customization, providing a very convenient and powerful solution in this regard, allowing us to easily implement this fine-grained template calling.Implement custom template calling for category or article detail pages, AnQiCMS mainly provides two main methods

2025-11-07

How to judge if a variable is empty in the template and display a default value?

During the presentation of web content, we often encounter such situations: a variable may be empty due to data loss, user failure to fill in, or other reasons.If you directly output these empty variables in the template, it may result in blank spaces on the page, affecting the appearance, or even cause layout errors, and may even expose unnecessary debugging information.It is particularly important to set a suitable default value for these variables that may be empty to ensure the completeness of website content display and the smoothness of user experience.The AnqiCMS uses a template engine syntax similar to Django

2025-11-07

How does AnQiCMS control the special display style of articles by setting the Flag attribute?

In Anqi CMS, the Flag attribute of the article is a very practical feature, which allows us to tag articles with special "labels" to display them uniquely on the website front-end.This mechanism greatly enhances the flexibility and diversity of content display, allowing website operators to easily control the display style and position of articles based on the importance, characteristics, or promotion needs of the content.What is the article Flag attribute? In simple terms, the Flag attribute is like a special "mark" that is attached to the article, it is not a category of the article

2025-11-07

How to automatically wrap long text for display in AnQiCMS templates?

During the operation of the AnQiCMS website, we often encounter scenarios where we need to display a large amount of text content, such as the main content of article detail pages, detailed descriptions of product introductions, or long introductions on category pages.These long texts, if not handled properly, may cause page layout to be disordered and affect the user's reading experience.Fortunately, AnQiCMS's powerful template engine provides various flexible ways to manage and display these long texts, including automatic line breaks and content truncation.AnQiCMS's template system has adopted the syntax of Django template engine, allowing us to use double curly braces

2025-11-07

How to automatically add watermarks to images in article content in AnQiCMS to protect copyright?

In today's era of increasingly rich digital content, the copyright protection of original images is particularly important.Whether it is a carefully photographed product image or an illustration drawn for an article, they all embody the creator's efforts and the brand image of the website.However, the situation where pictures are downloaded and used without permission is common, which not only violates copyright but may also dilute brand influence.Luckyly, AnQiCMS provides a convenient and efficient solution that helps us automatically add watermarks to images on the website, thereby effectively protecting original content.

2025-11-07

How to remove HTML tags in AnQiCMS template and display only plain text content?

When using AnQiCMS for content creation and display, we often need to flexibly control the presentation of content on the front end.Sometimes, the article or product description may contain rich HTML tags, which are used to provide beautiful layout on the detail page.

2025-11-07

How to display the current model name or URL alias in AnQiCMS?

In website content management, we often need to make the various parts of the website adapt and display information intelligently, one common requirement being how to dynamically display the name or URL alias of the current content model on the front-end page.This is crucial for improving user experience, optimizing search engine performance, and flexible management of website structure.AnQiCMS as an enterprise-level content management system provides a very flexible and powerful template tag function, making it intuitive and efficient to achieve this goal.

2025-11-07

How to display the list of internal titles (H1, H2, etc.) of the article content on the article detail page?

In Anqi CMS, in order to enhance the reading experience of long articles and the page SEO effect, we usually hope to display a list of internal titles (H1, H2, etc.) on the side or above the article content on the article detail page, which is what we usually call the article catalog or navigation.This makes it convenient for readers to quickly jump to the chapters of interest, and also helps search engines better understand the structure of the article. The AnQi CMS provides a very convenient way to implement this feature, the core lies in its powerful template tags and content field extraction capabilities.###

2025-11-07