How Do You Format Floating-Point Numbers in Go HTML/Templates?

Susan Sarandon
Release: 2024-11-06 02:39:02
Original
558 people have browsed it

How Do You Format Floating-Point Numbers in Go HTML/Templates?

Formatting Floats in Go HTML/Template

When working with floating-point numbers in Go templates, it is often necessary to format them for display purposes. Here are various methods for formatting floats in html/template:

1. Pre-formatting in Controller

Before passing the float to the template, you can format it in the controller using strconv.FormatFloat().

2. Custom Types

Create a custom type that implements the String() method, which formats the float to the desired precision. The template engine will automatically use this method for formatting.

3. Explicit printf in Template

You can call printf directly within the template and specify the desired format string.

4. Custom Function

Register a custom function that wraps the printf call with the desired format string. This avoids repeating the format string in the template.

Example:

Using the custom function approach in a Gin-Gonic backend:

func main() {
    router := gin.Default()
    router.GET("/", func(c *gin.Context) {
        data := map[string]interface{}{
            "n0": 3.1415,
            "n1": "%.2f", // Format string
        }
        c.HTML(http.StatusOK, "index.html", data)
    })
    router.Run()
}
Copy after login

In index.html:

Number: {{printf n1 n0}}
Copy after login

This will format the n0 float to 2 decimal places.

The above is the detailed content of How Do You Format Floating-Point Numbers in Go HTML/Templates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!