在 golang 中格式化 float html/template

Format float in golang html/template

我想在 golang html/template 文件中将 float64 值格式化为小数点后两位。在 .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

您可以注册一个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})
}

Playground

使用 printf template built-in function"%.2f" format:

tmpl := template.Must(template.New("test").Parse(`The formatted value is = {{printf "%.2f" .}}`))

tmpl.Execute(os.Stdout, 123.456789)

Go Playgroung

编辑:我错了rounding/truncating。

%.2f 格式的问题是它不舍入而是截断。

我开发了一个基于 int64 的小数 class 用于处理处理浮点数、字符串解析、JSON 等的货币

它将金额存储为 64 位整数美分。可以很容易地从浮动创建或转换回浮动。

存储在数据库中也很方便。

https://github.com/strongo/decimal

package example

import "github.com/strongo/decimal"

func Example() {
    var amount decimal.Decimal64p2; print(amount)  // 0

    amount = decimal.NewDecimal64p2(0, 43); print(amount)  // 0.43
    amount = decimal.NewDecimal64p2(1, 43); print(amount)  // 1.43
    amount = decimal.NewDecimal64p2FromFloat64(23.100001); print(amount)  // 23.10
    amount, _ = decimal.ParseDecimal64p2("2.34"); print(amount)  // 2.34
    amount, _ = decimal.ParseDecimal64p2("-3.42"); print(amount)  // -3.42
}

非常适合我的债务跟踪器应用 https://debtstracker.io/