在golang html/template中格式化float

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)

  • @dolmen好小费.关于`{{template}}`action:`{{template"name"}}`用`nil`数据执行模板,但你可以传递任何数据,例如`{{template"name".n0} }`,所以不需要用`{{with}}`包装.虽然,我认为执行另一个模板的性能比调用函数要差. (2认同)

dol*_*men 6

使用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)

去Playgroung