我想将float64值格式化为2小数位,在html/template中,例如在index.html文件中。在.go文件中,我可以格式化如下:
strconv.FormatFloat(value, 'f', 2, 32)但我不知道如何用模板格式化它。我在后端使用gin-gonic/gin框架。任何帮助都将不胜感激。谢谢。
发布于 2016-12-15 08:39:49
你有很多选择:
fmt.Sprintf() )之前使用n1。String() string方法的地方创建自己的类型,按自己的喜好格式化。这是由模板引擎(n2)检查和使用的。printf,并使用自定义格式字符串(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}}`输出(在围棋游乐场上尝试):
Number: n0 = 3.1415
Formatted: n1 = 3.14
Custom type: n2 = 3.14
Calling printf: n3 = 3.14
MyFormat: n4 = 3.14发布于 2017-02-01 13:41:39
发布于 2016-12-15 08:47:37
您可以注册一个FuncMap。
package main
import (
"fmt"
"os"
"text/template"
)
type Tpl struct {
Value float64
}
func main() {
funcMap := template.FuncMap{
"FormatNumber": func(value float64) string {
return fmt.Sprintf("%.2f", value)
},
}
tmpl, _ := template.New("test").Funcs(funcMap).Parse(string("The formatted value is = {{ .Value | FormatNumber }}"))
tmpl.Execute(os.Stdout, Tpl{Value: 123.45678})
}https://stackoverflow.com/questions/41159492
复制相似问题