How to use the `stringformat` filter to format a floating-point number as a string with two decimal places?

Calendar 👁️ 71

In website content display, precise and unified number presentation is crucial for user experience.For example, displaying product prices on e-commerce websites or presenting statistical percentages in data reports, if floating-point numbers are displayed directly without processing, it may result in overly long decimal places, which may appear unprofessional and untidy.Anqi CMS as an efficient content management system provides powerful template functions, among whichstringformatThe filter is a powerful tool to solve this problem.

The Anqi CMS template engine adopts a syntax similar to Django templates, which is known for its simplicity and power.In the template, we can use 'filters' to process variables in various ways, such as formatting, truncating, and converting.stringformatIt is one of the very practical filters, which can help us flexibly control the output format of numbers, strings, and other data, especially prominent in handling floating-point numbers.

stringformatThe primary role of the filter is to format any type of value into a string according to a specified pattern. If you are familiar with the function in Go language,fmt.Sprintf()then you understandstringformatThe principle of operation will be very easy, because their functions and usage are very similar. For floating-point numbers, we can use it to accurately control the display of decimal places.

How to format a floating-point number to two decimal places

To format a floating-point number to a string with two decimal places, we just need to add the template variable after|stringformat:"%.2f".

For example, assume that you have a content model namedPriceThe floating point field, if you want to display it as "12.34" on the front-end page instead of "12.345678", you can use it like this:

{{ item.Price|stringformat:"%.2f" }}

Here"%.2f"Is a formatted string, its meaning is:

  • %: Indicates that this is a formatted placeholder.
  • .2: Specifies that the decimal part of the floating-point number should be retained to two places.
  • fThis indicates that it is a float (float) type format.

Through this method, regardless ofitem.PriceThe original value is12.345678Or12.0It will be unified into12.35(usually rounded) or12.00Ensuring consistency in display.

Examples of actual application scenarios

Imagine you are building a product showcase page, where you need to display the price in the product list or detail page. In the Anqi CMS template files (for example, depending on your template directory structure, it may bearchive/detail.htmlIn a product list page, you might display product information like this:

{% archiveList products with type="list" limit="5" %}
    {% for product in products %}
    <div class="product-item">
        <h3>{{ product.Title }}</h3>
        <p>市场价:<del>{{ product.MarketPrice|stringformat:"%.2f" }} 元</del></p> {# 假设 MarketPrice 是浮点数 #}
        <p>销售价:<strong>{{ product.Price|stringformat:"%.2f" }} 元</strong></p> {# Price 同样是浮点数 #}
        <a href="{{ product.Link }}" class="view-details">查看详情</a>
    </div>
    {% endfor %}
{% endarchiveList %}

This code will traverse your product list and ensure that the 'market price' and 'sale price' of each product are displayed in a format that retains two decimal places, greatly enhancing the readability and consistency of the page.

It is not just about two decimal places:stringformatMore possibilities

stringformatThe strength of the filter is not limited to retaining two decimal places. You can adjust the formatting string according to your actual needs to achieve various display effects:

  • "%.0f":Do not retain decimal places, only show the integer part (which is usually rounded).
  • "%.4f":Retain four decimal places.
  • "%d":Convert the floating-point number to an integer (truncating the decimal part without rounding).
  • "%s"This will format the value into a plain string.
  • "%.2f%%"This will format into a percentage with two decimal places (e.g.,)12.34%)

This flexibility allowsstringformatto become an important tool for handling various data display needs.

In AnQi CMS,stringformatThe filter provides a simple and efficient way to control the display format of floating-point numbers.By precisely controlling the number of decimal places, it can make your website data display more professional and clear, thereby optimizing the user experience.Master this filter and it will make you more proficient in content operation.


Frequently Asked Questions (FAQ)

  1. Ask: How do I write a formatted string to keep three decimal places or not keep any decimals (just show integers)?Answer: To keep three decimal places, you can change the format string to"%.3f". For example:{{ value|stringformat:"%.3f" }}. If you want to display integers without decimals, you can use"%.0f", which will round the decimal part. For example:{{ value|stringformat:"%.0f" }}.

  2. Question:stringformatCan the filter handle non-numeric data types? What happens if the input is not a floating-point number?Answer:stringformatThe filter can handle multiple types of data and try to convert them according to the specified format. If the input is not a numeric type, such as a string or boolean, and you use a floating-point number%for integer%dformat specifier, it may try to perform a type conversion. If the conversion fails, it will usually output the default zero value (such as0.00or0Or else it will throw an error. Therefore, make sure the variable indeed contains a number before formatting floating-point numbers.

  3. Question: Besides,stringformatDoes AnQi CMS have other filters for floating-point number processing?Answer: Yes, AnQi CMS also providesfloatformatA filter that can also be used for floating-point formatting.floatformatThe default is to retain one decimal place, but if the decimal part is 0, it will not be displayed. You can also pass in parameters to specify the number of decimal places to retain. For example,{{ value|floatformat }}Retains one decimal place (if not zero),{{ value|floatformat:2 }}Retains two decimal places.floatformatThe behavior when handling trailing zeros is slightly different, you can choose to use it according to your specific needs.

Related articles

What is the practical use of the `dump` filter in AnQi CMS template debugging?

During the development and maintenance of Anqi CMS templates, we often encounter situations where some data cannot be displayed correctly or the variable structure does not match the expected one.How can one quickly and effectively find the source of the problem, which is a challenge facing every template developer.Fortunately, AnQi CMS provides an extremely useful tool—the `dump` filter, which can help us penetrate the true appearance of variables in the template like X-ray.What is the `dump` filter?

2025-11-08

How to display document, category, or single page associated image groups (such as Banner galleries) in Anqi CMS template?

At the time of building a website, exquisite image sets, such as carousel banners, are important elements to attract visitors' attention and display core content.AnQiCMS (AnQiCMS) provides flexible and powerful template functions, allowing you to easily display these groups of images associated with documents, categories, or single pages on the website.This article will delve into how to call and display these image groups in Anqi CMS templates, helping you better utilize visual content to enhance the attractiveness of your website.---###

2025-11-08

How to list all documents under a specific tag in AnQi CMS template and support pagination?

In a content management system, effectively organizing and displaying articles is the key to improving user experience.When content is categorized through tags, we often need to list all the articles under a specific tag on a page, and to maintain the cleanliness and loading speed of the page, pagination functionality also becomes indispensable.Strong and flexible template tags provided by AnQi CMS make this requirement easy to achieve.

2025-11-08

How to get the current page number, total number of pages, and home/last page links for the `pagination` tag?

AnQiCMS (AnQiCMS) is a powerful content management system that provides flexible and diverse ways to display content when building a website.Among them, the pagination function is crucial for list pages with a large amount of content, as it not only improves the user experience but also optimizes the website performance.Proficiently use the `pagination` tag, which can help us accurately control the display logic of pagination, thereby creating a more user-friendly and professional website.

2025-11-08

How to define the `stringformat` filter using Go's `fmt.Sprintf` format?

In AnQi CMS template design, the flexibility of data display is a key aspect that template developers highly value.The system is built-in with multiple filters (Filters) to process and format variables.Among them, the `stringformat` filter is a versatile tool that allows us to control the output format of any type of data with the powerful format definitions of the Go language `fmt.Sprintf` function, whether it is numbers, strings, or more complex data structures, all can be displayed in the expected style.What is

2025-11-08

How to remove specific characters or spaces from the beginning and end of a string in AnQiCMS template?

When using AnQiCMS for website content management, we often encounter situations where we need to refine the output strings in the template.For example, the text obtained from the database may contain unnecessary leading and trailing spaces, or in some specific scenarios, it may be necessary to remove the specific symbols from the beginning or end of the string to ensure the neat display of the page and the uniformity of data format.The powerful template engine of AnQi CMS provides a variety of practical filters that can easily handle these string processing requirements.

2025-11-08

How to display the latest published article list on the homepage of AnQiCMS?

In Anqi CMS, the homepage carries the important responsibility of attracting visitors and displaying the latest news.Generally, displaying the latest list of published articles in a prominent position on the homepage is an effective way to enhance user experience and guide content browsing.AnQi CMS with its flexible template system and powerful content management features makes this operation very direct and efficient.

2025-11-08

How to customize the title display format of AnQi CMS article detail page?

The secret to flexibly customizing the CMS article detail page title display formatIt not only affects the identification of users in browser tabs and favorites, but is also one of the key elements of search engine optimization (SEO).A clear, attractive, and well-formatted title that can effectively improve the click-through rate of the article and the professional image of the website.

2025-11-08