在golang html / template中格式化float [英] Format float in golang html/template
问题描述
我想将 float64
值格式化为golang html / template
中的2个小数位c> index.html 文件。在 .go
文件中,我可以格式化为:
strconv.FormatFloat值,'f',2,32)
但是我不知道如何格式化模板。我为后端使用 gin-gonic / gin
框架。任何帮助将不胜感激。感谢您。
您有很多选择:
fmt.Sprintf()
将它传递给模板执行( n1
)
String()字符串
方法,根据自己的喜好进行格式化。这由模板引擎( n2
)检查和使用。
printf < (code> n3
)。
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 %2.f,3.1415),
n2:MyFloat(3.1415),
n3:3.1415,
n4:3.1415,
}
如果err:= t.Execute(os.Stdout,m); err!= nil {
fmt.Println(err)
}
}
const templ =`
Number:n0 = {{.n0} }
格式化:n1 = {{.n1}}
自定义类型:n2 = {{.n2}}
调用printf:n3 = {{printf%.2f.n3} }
MyFormat:n4 = {{MyFormat .n4}}`
输出在去游乐场):
编号:n0 = 3.1415
格式:n1 = 3.14
自定义类型:n2 = 3.14
调用printf:n3 = 3.14
MyFormat:n4 = 3.14
I want to format float64
value to 2 decimal places in golang html/template
say in index.html
file. In .go
file I can format like:
strconv.FormatFloat(value, 'f', 2, 32)
But I don't know how to format it in template. I am using gin-gonic/gin
framework for backend. Any help will be appreciated. Thanks.
You have many options:
- You may decide to format the number e.g. using
fmt.Sprintf()
before passing it to the template execution (n1
) - Or you may create your own type where you define the
String() string
method, formatting to your liking. This is checked and used by the template engine (n2
). - You may also call
printf
directly and explicitly from the template and use custom format string (n3
). - Even though you can call
printf
directly, this requires to pass the formatstring
. If you don't want to do this every time, you can register a custom function doing just that (n4
)
See this example:
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}}`
Output (try it on the Go Playground):
Number: n0 = 3.1415
Formatted: n1 = 3.14
Custom type: n2 = 3.14
Calling printf: n3 = 3.14
MyFormat: n4 = 3.14
这篇关于在golang html / template中格式化float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!