Search code examples
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:

    • You may decide to format the number e.g. using fmt.Sprintf() before passing it to the template execution (n1)
    • Or you may create your own type where you define the String() string method, formatting to your liking. This is checked and used by the template engine (n2).
    • You may also call printf directly and explicitly from the template and use custom format string (n3).
    • Even though you can call printf directly, this requires to pass the format string. If you don't want to do this every time, you can register a custom function doing just that (n4)

    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