您有很多选择:
- 您可以决定将数字格式化,例如使用,
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.14Custom type: n2 = 3.14Calling printf: n3 = 3.14MyFormat: n4 = 3.14



