In the presentation of website content, the formatting of numbers is often a key detail that reflects professionalism.Whether it is the price of goods, statistical data, or financial statements, controlling the output of decimal places accurately can not only improve the user experience but also ensure the accuracy of information.stringformatThe filter is the powerful assistant to solve this problem.

stringformatThe filter: A universal tool for precise number formatting.

stringformatThe filter is a powerful and flexible tool in Anqi CMS template, allowing us to output various types of data, including numbers, strings, and even more complex data structures, in a predefined format. Its core mechanism is similar to the built-in Go language.fmt.Sprintf()A function, which means it inherits the powerful formatting output capabilities of the Go language, especially the precise control of decimal places of numbers.

Basic usage and precise decimal place control

UsestringformatThe filter is very direct, its syntax structure is usually{{ 变量 | stringformat:"格式字符串" }}. Among them, the 'format string' is the key to defining the output style.

when we need to control the decimal places of numbers accurately,stringformatThe filter can really shine. We can use floating-point formatting to verbalize.%fAnd its variants to achieve the purpose:

  • Specify the number of decimal places: Pass%.nfIn such a format,nRepresents the number of decimal places you want to retain. For example,%.2fmeans retaining two decimal places.
    • Assuming we have a variableprice = 3.141592653.
    • {{ price | stringformat:"%.2f" }}will output3.14.
    • {{ price | stringformat:"%.4f" }}it will output3.1416.
    • It is worth noting that,stringformatRounding is usually performed when dealing with decimal places.
  • Force decimal places to be displayed: Even if the number is an integer or the decimal part ends with zero,stringformatit can still force the display of a specified number of decimal places.
    • Ifamount = 100.
    • {{ amount | stringformat:"%.2f" }}will output100.00This is very useful for displaying amount data, it can maintain a unified visual effect.
    • Ifdiscount = 12.50.
    • {{ discount | stringformat:"%.2f" }}It will still output12.50without omitting the trailing zeros.
  • Do not display decimal placesSometimes we want to truncate a floating-point number to an integer without showing any decimal.
    • {{ 123.789 | stringformat:"%.0f" }}will output124(It will also be rounded off accordingly).

By using these flexible format strings, we can easily control the precision of decimal place output in templates.

More than just decimal places:stringformatother capabilities

In addition to precise control of decimal places,stringformatThe filter also has more extensive formatting capabilities, which is due to its underlying support for Go languagefmt.Sprintf()functions. For example:

  • Formatting integers:{{ 888 | stringformat:"Test: %d" }}You can format integers and embed them in strings, outputTest: 888.
  • Get data type:{{ some_variable | stringformat:"%T" }}You can easily get the data type of a variable.
  • Hexadecimal output:{{ 255 | stringformat:"%x" }}It will convert decimal numbers255Formatted as hexadecimalff.
  • Control width and alignment: By adding numbers before the format verb, you can control the minimum width of the output, achieving text alignment effects.

These features enablestringformatIt is not just a number formatting tool, but also a general data presentation controller.

Application scenarios and precautions

stringformatFilters are very practical in many website operation scenarios. For example:

  • E-commerce website: Standardize the display format of product prices, shipping fees, etc., such as$123.45.
  • Data report: Format percentages, averages, and other statistical data to ensure that the report is clear and readable.
  • Multilingual siteIn different language environments, numbers are formatted according to habit.

While usingstringformatThere are also some minor details to pay attention to when doing so:

  1. Accuracy of the format string: Because it is based onfmt.Sprintf()Therefore, the format string must comply with the specification of the Go language. Incorrect formatting may cause errors or unexpected output.
  2. Type of input data: AlthoughstringformatAttempts to perform type conversion, but **practice is to ensure that the data type you provide is compatible with the expected format string, such as using for floating-point numbers%fa series format.
  3. The output is a string:stringformatAlways convert the result to a string.This means that when performing subsequent mathematical operations on formatted data, it is necessary to perform type conversion, or to complete all calculations before formatting.

MasterstringformatThe filter helps us present the numeric information in the website content more finely and professionally, thereby enhancing the overall user experience and the professional image of the website.


Frequently Asked Questions (FAQ)

1.stringformatFilters andfloatformatWhat are the differences between the filters? Which one should I choose?

floatformatThe filter is specifically designed for floating-point numbers, mainly used to control the decimal places of floating-point numbers, by default it retains one non-zero decimal, and can also specify the number of digits to be retained. AndstringformatA filter is a more general formatting tool that can handle various types of data such as numbers, strings, and provides Go languagefmt.Sprintf()The powerful formatting capabilities of the syntax, including finer decimal place control, width alignment, type display, etc. If your need is to simply format the decimal places of floating-point numbers, floatformatIt might be more concise and easy to use; however, if you need more flexible formatting rules or need to handle non-float number types, thenstringformatundoubtedly, it is a more powerful choice.

2. I have an integer100How to usestringformatThe filter displays it as100.00?

You can directly use the formatting rules for floating-point numbers to achieve this purpose.stringformatThe filter will intelligently convert integers to floating-point numbers before formatting. Therefore,{{ 100 | stringformat:"%.2f" }}It will output100.00This is very useful for maintaining consistency in the display of amounts or other numbers that require fixed decimal places.

3.stringformatCan a filter be used to format dates and times? For example, to convert a Unix timestamp into a readable date string?

stringformatThe filter itself is based onfmt.Sprintf()A general data formatting tool, it mainly handles basic types such as numbers and strings. For date and time, especially Unix timestamps, AnQiCMS provides specialstampToDatefilter.stampToDateThe filter can directly convert a Unix timestamp (10-digit integer) to a date-time string in a specified format. For example,{{ stampToDate(某个时间戳, "2006-01-02 15:04:05") }}it can format the timestamp to年-月-日 时:分:秒The format. Therefore, it is recommended to usestampToDateto handle date and time formatting, as it is more intuitive and professional.