Greetings Gophers,
I am quite new to Go so forgive my ignorance. I have been looking at some examples on the net, but have run into something which I do not understand.
I will paste the code here, and the result afterwards:
package main
import (
"fmt"
"os"
"text/template"
)
type Inventory struct {
Material string
Count uint
Price float32
}
func main() {
sweaters := Inventory{"wool", 17, 19.20}
shoes := Inventory{"leather", 5, 11.35}
tmpl, err := template.New("test").Parse("{{.Count}} items of {{.Material}}, price {{.Price}}")
if err != nil {
fmt.Println(err)
}
fmt.Println("Sweaters:", sweaters)
fmt.Println("Shoes:", shoes)
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil {
fmt.Println(err)
}
err = tmpl.Execute(os.Stdout, shoes)
if err != nil {
fmt.Println(err)
}
}
/usr/local/go/bin/go build [/Users/jre/go/src/jre/template1]
Success: process exited with code 0.
/Users/jre/go/src/jre/template1/template1 [/Users/jre/go/src/jre/template1]
Sweaters: {wool 17 19.2}
Shoes: {leather 5 11.35}
17 items of wool, price 19.25 items of leather, price 11.35Success: process exited with code 0.
My two queries:
- How does one ‘print’ a float value with two decimal places using text/template? I imagine this is in the docs somewhere, but I haven’t seen it yet.
- You can see when I directly print the sweaters struct it shoes 19.2, but when using text/template it shows as 19.25. I can see by trial and error that it is picking up the second decimal place from the shoes struct. My question is why is it doing that? I know this is not the best way to write this code, and I should put it into a loop, but it is interesting to me that the second decimal place has been altered at all.
Many thanks,
JRE.