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() }
In index.html:
Number: {{printf n1 n0}}
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!