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.
You have many options:
fmt.Sprintf()
before passing it to the template execution (n1
)String() string
method, formatting to your liking. This is checked and used by the template engine (n2
).printf
directly and explicitly from the template and use custom format string (n3
).printf
directly, this requires to pass the formatstring
. If you don't want to do this every time, you can register a custom function doing just that (n4
)See this example:
Output (try it on the Go Playground):
Use the
printf
template built-in function with the"%.2f" format
:Go Playgroung
Edit: I was wrong about rounding/truncating.
The problem with%.2f
formatting is that it does not round but truncates.I've developed a decimal class based on int64 for handling money that is handling floats, string parsing, JSON, etc.
It stores amount as 64 bit integer number of cents. Can be easily created from float or converted back to float.
Handy for storing in DB as well.
https://github.com/strongo/decimal
Works well for my debts tracker app https://debtstracker.io/
You can register a
FuncMap
.Playground