In website content display, precise and unified number display is crucial for user experience.For example, when 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 too many decimal places, making it look unprofessional and cluttered.stringformatThe filter is a powerful tool to solve this problem.

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

stringformatThe main function of the filter is to format any type of value into a string according to the specified pattern. If you are familiar with the Go language,fmt.Sprintf()function, then it is easy to 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 precisely 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|stringformat:"%.2f".

For example, assume you have a content model with a name ofPriceThe floating-point number 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 are the"%.2f"It is a formatted string, its meaning is:

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

In this way, no matteritem.PriceThe original value is12.345678Or12.0, it will be unified formatted as12.35(usually rounded) or12.00, ensuring consistency in display.

Examples of practical application scenarios

Imagine you are building a product showcase page and 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 some product list page), you may get and 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 iterate through your product list and ensure that each product's 'Market Price' and 'Sale Price' are displayed in a format with two decimal places, greatly enhancing the readability of the data and the consistency of the page.

Not just two decimal places:stringformatMore possibilities:

stringformatThe power 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 (it will usually be rounded up).
  • "%.4f":Retain four decimal places.
  • "%d":Convert floating-point numbers to integers (the decimal part will be truncated, not rounded up).
  • "%s":Format the value into a common string.
  • "%.2f%%":Format as a two decimal places with a percentage sign (e.g.,)12.34%).

This flexibility allowsstringformatis an important tool for handling various data display requirements.

In the Anqi CMS,stringformatThe filter provides us with a simple and efficient way to control the display format of floating-point numbers.Through precise control of decimal places, you can make your website data display more professional and clear, thereby optimizing the user experience.Grasp this filter and it will enable you to operate content with greater ease.


Common Questions (FAQ)

  1. 问:How should I write the formatted string to keep three decimal places or not display decimals (only show integers)?答:To retain three decimal places, you can change the format string to"%.3f". For example:{{ value|stringformat:"%.3f" }}. If you want to display integers without retaining decimals"%.0f", it will round off the decimal part. For example:{{ value|stringformat:"%.0f" }}.

  2. Q:stringformatFilter can handle non-numeric data? What if the input is not a floating-point number?Answer:stringformatThe filter can handle multiple types of data and try to convert them into the specified format. If the input is not a numeric type, such as a string or a boolean, and you use a floating-point number%fOr integer%dThe format symbol, which might try to perform a type conversion. If the conversion fails, it will usually output the default zero value (such as0.00or0)or directly report an error. Therefore, make sure the variable indeed contains a number before formatting a floating-point number.

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