在golang html / template中格式化float
我想将float64
值格式化为golang
html/template
在index.html
文件中说的2个小数位。在.go
文件中,我可以像这样格式化:
strconv.FormatFloat(value, 'f', 2, 32)
但是我不知道如何在模板中格式化它。我正在使用gin-gonic/gin
后端框架。任何帮助将不胜感激。谢谢。
回答:
您有很多选择:
- 您可以决定将数字格式化,例如使用,
fmt.Sprintf()
然后再将其传递给模板执行(n1
) - 或者,您可以在定义
String() string
方法的地方创建自己的类型,并根据自己的喜好格式化。模板引擎(n2
)对此进行了检查和使用。 - 您也可以
printf
直接从模板直接调用,并使用自定义格式字符串(n3
)。 - 即使您可以
printf
直接调用,也需要传递formatstring
。如果您不想每次都这样做,可以注册一个自定义函数来执行此操作(n4
)
请参阅以下示例:
type MyFloat float64func (mf MyFloat) String() string {
return fmt.Sprintf("%.2f", float64(mf))
}
func main() {
t := template.Must(template.New("").Funcs(template.FuncMap{
"MyFormat": func(f float64) string { return fmt.Sprintf("%.2f", f) },
}).Parse(templ))
m := map[string]interface{}{
"n0": 3.1415,
"n1": fmt.Sprintf("%.2f", 3.1415),
"n2": MyFloat(3.1415),
"n3": 3.1415,
"n4": 3.1415,
}
if err := t.Execute(os.Stdout, m); err != nil {
fmt.Println(err)
}
}
const templ = `
Number: n0 = {{.n0}}
Formatted: n1 = {{.n1}}
Custom type: n2 = {{.n2}}
Calling printf: n3 = {{printf "%.2f" .n3}}
MyFormat: n4 = {{MyFormat .n4}}`
输出(在Go Playground上尝试):
Number: n0 = 3.1415Formatted: n1 = 3.14
Custom type: n2 = 3.14
Calling printf: n3 = 3.14
MyFormat: n4 = 3.14
以上是 在golang html / template中格式化float 的全部内容, 来源链接: utcz.com/qa/409151.html