How to always display product prices (floating point numbers) with two decimal places in AnQiCMS templates?

Calendar 👁️ 61

When operating a product display website, you may often encounter situations where you need to accurately display product prices. A professional and user-friendly website often requires a unified display format for product prices, such as always retaining two decimal places, even for integer prices that are automatically filled in..00。AnQiCMS with its flexible template system makes dealing with these details very convenient.

Understand the data and display in AnQiCMS templates.

The AnQiCMS template system is based on Go language, but its syntax style is very similar to the Django template engine, which allows you to quickly get started if you are familiar with web development. In AnQiCMS, products or any content with price attributes are usually processed througharchiveDetail(Get single document details) orarchiveListUse tags like (Get document list) to get data.

For example, when you go througharchiveListtags to cycle through products, you might get aitemAn object that containsitem.Title(Product title) anditem.Price(Product price) and other fields. At this point,item.Priceit may be a floating-point number, such as12.345/12.3even12. Our goal is to display it in the form of12.35/12.30or12.00.

Core Solution: Use Filters

In the AnQiCMS template, handling variable display formats mainly relies on the powerful "Filters" feature.The filter can perform various operations on the output variable value, including formatting, truncation, conversion, etc.For the need to retain two decimal places for floating-point prices, AnQiCMS provides several very practical filters.

Method one:floatformatFilter

floatformatFilters are specifically used to format floating-point numbers, allowing you to specify the number of decimal places to retain.

How to use:

{{ item.Price|floatformat:2 }}

Here2means retaining two decimal places.

Effect Demonstration:

  • Ifitem.PriceIs12.345The output will be12.35Rounded automatically.
  • Ifitem.PriceIs12.3The output will be12.3.
  • Ifitem.PriceIs12.00The output will be12.
  • Ifitem.PriceIs12The output will be12.

As you can see,floatformatPerforms well when handling numbers with decimals, but for decimals ending in zero (such as12.30) or integers, it will omit the zeros after the decimal point, displaying them as12.3or12. If you want to even force integers to display with two decimal places (for example12.00), then you need to consider another method.

Method two:stringformatFilter (recommended)

stringformatThe filter provides more flexible formatting capabilities, similar to the function in Go language,fmt.Sprintf()which allows you to use formatting strings to control the output precisely. This is useful foralwaysIt is very suitable for scenarios that require two decimal places.

How to use:

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

Here%.2fIt is a formatted string that tells the template engine to format the floating-point number (f) to two decimal places in total (.2) and it will automatically fill in the zeros after the decimal point.

Effect Demonstration:

  • Ifitem.PriceIs12.345The output will be12.35Rounded automatically.
  • Ifitem.PriceIs12.3The output will be12.30.
  • Ifitem.PriceIs12.00The output will be12.00.
  • Ifitem.PriceIs12The output will be12.00.

stringformatThe filter is especially useful in scenarios where it is necessary to strictly maintain two decimal places, as it forces the zero after the decimal point to be filled in, making the price display more unified and professional.

Actual application example

Assuming you are creating a product list page template, you want each product's price to be displayed neatly with two decimal places. You can organize your template code like this:

<div class="product-list">
    {# 获取产品列表,假设moduleId="2"代表产品模型,limit="5"限制显示5个产品 #}
    {% archiveList products with moduleId="2" limit="5" %}
        {% for item in products %}
            <div class="product-item">
                <a href="{{ item.Link }}" class="product-link">
                    {# 假设产品Logo存在 #}
                    {% if item.Logo %}
                        <img src="{{ item.Logo }}" alt="{{ item.Title }}" class="product-thumb">
                    {% endif %}
                    <h3 class="product-title">{{ item.Title }}</h3>
                    {# 使用 stringformat 过滤器确保价格始终显示两位小数 #}
                    <p class="product-price">价格: ¥ {{ item.Price|stringformat:"%.2f" }}</p>
                    {# 假设产品有简介,并希望截取显示 #}
                    <p class="product-description">{{ item.Description|truncatechars:100 }}</p>
                </a>
            </div>
        {% empty %}
            <p>暂无产品信息。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

Through this code, regardless of how your product prices are stored in the background, the front-end page will display them in a unified two-digit decimal format, thereby enhancing the professionalism and user experience of the website.

Summary

ByfloatformatorstringformatThese simple and powerful filters allow you to easily control the display format of floating-point prices in AnQiCMS templates. When it is necessary to strictly maintain two decimal places, even including padding.00In this context,stringformat:"%.2f"The filter is undoubtedly the better choice, as it helps your website present a more professional and consistent visual effect.


Frequently Asked Questions (FAQ)

1. Why do I need to display integer prices as10.00This form, rather than simple10?

On websites that have strict requirements for displaying prices, such as e-commerce or financial websites, a unified price format can enhance user trust and the professionalism of the website. The10displayed as10.00It can avoid potential misunderstandings (for example, users may think that)10The price is not fully displayed, and visually maintains the alignment and consistency of all product prices, especially in lists or tables.

Related articles

What are the main differences between AnQiCMS's `date` and `stampToDate` filters when handling date data?

In AnQiCMS template development, displaying time data is an indispensable part, whether it is the publication time of articles, the update date of products, or the time records of user behavior, it needs to be presented to the user in a clear and readable manner.To meet the different time processing needs, AnQiCMS provides two core filters: `date` and `stampToDate`.

2025-11-07

How to format a 10-digit timestamp retrieved from the database into a custom date-time format in AnQiCMS template?

In website content display, we often encounter time data in a long string of numbers from the database, such as `1678886400`. This string of numbers, which is what we commonly call a timestamp, is very convenient for computers, but it seems cold and difficult to understand for users visiting websites.Fortunately, AnQi CMS provides us with a very convenient feature that can easily convert these original 10-digit timestamps into the date and time format we are accustomed to reading.

2025-11-07

How to set a default friendly display value for a possibly empty variable in AnQiCMS template?

When building website templates, we often encounter situations where a variable may be empty in the template due to unentered data, optional fields left blank, or specific business logic.If these empty variables are not processed, the front-end page of the website may appear blank areas, display unfriendly placeholders, and even cause layout errors, thereby affecting user experience and the professionalism of the website.

2025-11-07

What is the correct syntax for using the `{{ obj|filter__name:param }}` filter in AnQiCMS templates?

AnQiCMS (AnQiCMS) provides strong support for content operations with its efficient and flexible features.In daily content display, we often need to process and format data in a fine-grained manner to ensure that information is presented to visitors in a **state**.At this moment, the 'filter' in the template has become an indispensable tool for us. Today, let's delve into the correct syntax for using filters in Anqi CMS templates: `{{ obj|filter_name:param }}`.Understand and master it

2025-11-07

How does AnQiCMS automatically identify URLs or email addresses in text and convert them into clickable hyperlinks?

In the daily operation of websites, we often need to add various links in article content, such as URLs pointing to external resources, or email addresses for easy reader contact.Manually adding hyperlinks one by one is not only inefficient but also prone to errors.Fortunately, AnQiCMS provides very practical features that can intelligently identify URLs and email addresses in text and automatically convert them into clickable hyperlinks, greatly enhancing the efficiency and user experience of content editing.

2025-11-07

How to control the truncation length of the hyperlink text when using the AnQiCMS `urlizetrunc` filter?

In website content operation, we often need to display various hyperlinks in articles, comments, or list pages.These links may be pointing to other content within the site, external resources, or the contact email of the user.However, some excessively long links may not only destroy the page layout, affect the aesthetics, but may also reduce the user's reading experience.Especially in limited display space, long URLs can make content look disorganized.

2025-11-07

Why does the AnQiCMS template default to escaping HTML code? How can HTML content be safely output?

When using AnQiCMS for template development, we may notice an interesting phenomenon: sometimes, the HTML code directly output in the template, such as a `<div>` tag, is not parsed by the browser into a visible area as expected, but is displayed exactly as it is, showing `&lt;div &gt; `such characters. This may be confusing, why does AnQiCMS default to escaping HTML code?How can we safely output the HTML content we want?--- ### One

2025-11-07

How to quickly split a comma-separated string into an array for traversal in AnQiCMS template?

In website content operation, we often encounter such situations: a content field stores a series of interconnected information, usually connected by commas.For example, an article may be associated with multiple tags ("SEO, website optimization, content marketing"), a product may have various color options ("red, blue, green"), or you may need to display a set of user-defined keywords.How to efficiently convert the comma-separated strings to traversable data structures when we need to display them one by one on the front-end page or perform more complex processing

2025-11-07