Home >Backend Development >Golang >How to Format Float Values in Go HTML Templates?

How to Format Float Values in Go HTML Templates?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 01:25:02971browse

How to Format Float Values in Go HTML Templates?

Format Float in Go Templates

Formatting float64 values in Go HTML templates can be done using multiple methods.

1. Pre-Format the Float

Format the float using fmt.Sprintf() before passing it to the template:

func main() {
  t := template.New("")
  data := map[string]interface{}{
    "value": strconv.FormatFloat(3.1415, 'f', 2, 32),
  }
  _ = t.Execute(os.Stdout, data) // Render the template with formatted value
}

2. Create a String() Function

Define a custom type with a String() method that formats the value to your liking:

type MyFloat struct {
  value float64
}

func (f MyFloat) String() string {
  return fmt.Sprintf("%.2f", f.value)
}

func main() {
  t := template.New("")
  data := map[string]interface{}{
    "value": MyFloat{3.1415},
  }
  _ = t.Execute(os.Stdout, data) // Render the template with custom type
}

3. Call printf() in Template

Call printf() in the template using a custom format string:

{{printf "%.2f" .value}}

4. Register a Custom Function

Register a custom function to simplify the formatting process:

tmpl := template.New("")
tmpl = tmpl.Funcs(template.FuncMap{
  "myFormat": func(f float64) string {
    return fmt.Sprintf("%.2f", f)
  },
})

func main() {
  data := map[string]interface{}{
    "value": 3.1415,
  }
  _ = tmpl.Execute(os.Stdout, data) // Render the template using custom function
}

In the template:

{{myFormat .value}}

The above is the detailed content of How to Format Float Values in Go HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn