go - 在 golang html/模板中格式化 float

标签 go format go-html-template

我想将 float64 值格式化为 golang html/template 中的 2 位小数,例如在 index.html 文件中。在 .go 文件中,我可以像这样格式化:

strconv.FormatFloat(value, 'f', 2, 32)

但我不知道如何在模板中格式化它。我正在为后端使用 gin-gonic/gin 框架。任何帮助将不胜感激。谢谢。

最佳答案

你有很多选择:

  • 您可以决定格式化数字,例如使用 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}}`

输出(在 Go Playground 上尝试):

Number:         n0 = 3.1415
Formatted:      n1 = 3.14
Custom type:    n2 = 3.14
Calling printf: n3 = 3.14
MyFormat:       n4 = 3.14

关于go - 在 golang html/模板中格式化 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159492/

相关文章:

mysql - 使用 MySQL 5.6 和 GORM 的递归表中的外键约束失败

database - 如何使用 Gorm 预加载

format - Common Lisp格式指令中出现神秘的换行符

javascript - jQuery 电话正则表达式验证

html - golang html模板格式不正确

go - 调试Go程序时VSCode错误的路径

Go环境变量设置后保持不变

Javascript 千位分隔符/字符串格式

http - Golang 在等待数据加载时显示静态 HTML 模板

go - 如何访问在GOHTML模板中动态创建的行?