How to Format Float Values in Go HTML Templates?

Mary-Kate Olsen
Release: 2024-11-08 01:25:02
Original
829 people have browsed it

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
}
Copy after login

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
}
Copy after login

3. Call printf() in Template

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

{{printf "%.2f" .value}}
Copy after login

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
}
Copy after login

In the template:

{{myFormat .value}}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!