Bha*_*ana 11 format go go-html-template
我想格式化float64值在golang 2位小数html/template中说index.html文件.在.go文件中,我可以格式化为:
strconv.FormatFloat(value, 'f', 2, 32)
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在模板中格式化它.我正在使用gin-gonic/gin框架进行后端.任何帮助将不胜感激.谢谢.
icz*_*cza 16
你有很多选择:
fmt.Sprintf()在将其传递给模板执行之前使用(n1)String() string方法,根据自己的喜好进行格式化.这由模板引擎(n2)检查和使用.printf直接从模板中明确调用并使用自定义格式string(n3).printf直接呼叫,也需要传递格式string.如果你不想每次都这样做,你可以注册一个自定义函数(n4)看这个例子:
type MyFloat float64
func (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}}`
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
Number: n0 = 3.1415
Formatted: n1 = 3.14
Custom type: n2 = 3.14
Calling printf: n3 = 3.14
MyFormat: n4 = 3.14
Run Code Online (Sandbox Code Playgroud)
使用printf 内置函数模板用"%.2f" format:
tmpl := template.Must(template.New("test").Parse(`The formatted value is = {{printf "%.2f" .}}`))
tmpl.Execute(os.Stdout, 123.456789)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8653 次 |
| 最近记录: |