栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在golang html / template中格式化float

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在golang html / template中格式化float

您有很多选择:

  • 您可以决定将数字格式化,例如使用,
    fmt.Sprintf()
    然后再将其传递给模板执行(
    n1
  • 或者,您可以在定义
    String() string
    方法的地方创建自己的类型,并根据自己的喜好格式化。模板引擎(
    n2
    )对此进行了检查和使用。
  • 您也可以
    printf
    直接从模板直接调用,并使用自定义格式字符串(
    n3
    )。
  • 即使您可以
    printf
    直接调用,也需要传递format
    string
    。如果您不想每次都这样做,可以注册一个自定义函数来执行此操作(
    n4

请参阅以下示例:

type MyFloat float64func (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.1415Formatted:      n1 = 3.14Custom type:    n2 = 3.14Calling printf: n3 = 3.14MyFormat:       n4 = 3.14


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383376.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号