goformatgo-html-template

Format float in golang html/template


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.


Solution

  • You have many options:

    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