Format float in golang html/template

pdsfdshx  于 2023-11-14  发布在  Go
关注(0)|答案(4)|浏览(106)

我想在index.html文件中将float64的值格式化为2个小数位。在.go文件中,我可以格式化为:

  1. strconv.FormatFloat(value, 'f', 2, 32)

字符串
但我不知道如何在模板格式。我使用gin-gonic/gin框架的后端。任何帮助将不胜感激。谢谢。

1cosmwyk

1cosmwyk1#

你有很多选择:

  • 您可以决定格式化数字,例如在将其传递给模板执行之前使用fmt.Sprintf()n1
  • 或者你也可以创建自己的类型,在这里你定义了String() string方法,根据你的喜好格式化。这是由模板引擎(n2)检查和使用的。
  • 您也可以直接从模板中显式调用printf,并使用自定义格式字符串(n3)。
  • 即使你可以直接调用printf,这也需要传递格式string。如果你不想每次都这样做,你可以注册一个自定义函数来做这件事(n4)。

请看这个例子:

  1. type MyFloat float64
  2. func (mf MyFloat) String() string {
  3. return fmt.Sprintf("%.2f", float64(mf))
  4. }
  5. func main() {
  6. t := template.Must(template.New("").Funcs(template.FuncMap{
  7. "MyFormat": func(f float64) string { return fmt.Sprintf("%.2f", f) },
  8. }).Parse(templ))
  9. m := map[string]interface{}{
  10. "n0": 3.1415,
  11. "n1": fmt.Sprintf("%.2f", 3.1415),
  12. "n2": MyFloat(3.1415),
  13. "n3": 3.1415,
  14. "n4": 3.1415,
  15. }
  16. if err := t.Execute(os.Stdout, m); err != nil {
  17. fmt.Println(err)
  18. }
  19. }
  20. const templ = `
  21. Number: n0 = {{.n0}}
  22. Formatted: n1 = {{.n1}}
  23. Custom type: n2 = {{.n2}}
  24. Calling printf: n3 = {{printf "%.2f" .n3}}
  25. MyFormat: n4 = {{MyFormat .n4}}`

字符串
输出(在Go Playground上尝试):

  1. Number: n0 = 3.1415
  2. Formatted: n1 = 3.14
  3. Custom type: n2 = 3.14
  4. Calling printf: n3 = 3.14
  5. MyFormat: n4 = 3.14

展开查看全部
zmeyuzjn

zmeyuzjn2#

printf模板内置函数与"%.2f" format一起使用:

  1. tmpl := template.Must(template.New("test").Parse(`The formatted value is = {{printf "%.2f" .}}`))
  2. tmpl.Execute(os.Stdout, 123.456789)

字符串
Go Playgroung

31moq8wy

31moq8wy3#

您可以注册FuncMap

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "text/template"
  6. )
  7. type Tpl struct {
  8. Value float64
  9. }
  10. func main() {
  11. funcMap := template.FuncMap{
  12. "FormatNumber": func(value float64) string {
  13. return fmt.Sprintf("%.2f", value)
  14. },
  15. }
  16. tmpl, _ := template.New("test").Funcs(funcMap).Parse(string("The formatted value is = {{ .Value | FormatNumber }}"))
  17. tmpl.Execute(os.Stdout, Tpl{Value: 123.45678})
  18. }

字符串
Playground

展开查看全部
q1qsirdb

q1qsirdb4#

编辑:我对舍入/截断的看法是错误的。

%.2f的问题是它不舍入而是截断。
我开发了一个基于int 64的decimal类来处理货币,它处理浮点数、字符串解析、JSON等。
它将金额存储为64位整数美分。可以很容易地从浮点数创建或转换回浮点数。
也可以存储在DB中。
https://github.com/strongo/decimal

  1. package example
  2. import "github.com/strongo/decimal"
  3. func Example() {
  4. var amount decimal.Decimal64p2; print(amount) // 0
  5. amount = decimal.NewDecimal64p2(0, 43); print(amount) // 0.43
  6. amount = decimal.NewDecimal64p2(1, 43); print(amount) // 1.43
  7. amount = decimal.NewDecimal64p2FromFloat64(23.100001); print(amount) // 23.10
  8. amount, _ = decimal.ParseDecimal64p2("2.34"); print(amount) // 2.34
  9. amount, _ = decimal.ParseDecimal64p2("-3.42"); print(amount) // -3.42
  10. }

字符串

展开查看全部

相关问题