I am using the gin gonic framework and have built a JSON API.
I have a new end point I want to make but one of the values is a decimal. I created the following struct:
type AcceptedTerms struct {
Id int64
FirstName string
LastName string
Fee ***DECIMAL***
Date *time.Time
}
My controller snippets of code:
query = "SELECT " +
"AcceptedTerms.* " +
"FROM AcceptedTerms " +
"ORDER BY " + sort_by + " " + order_by +
" LIMIT " + limit2 +
" OFFSET " + offset2`
_, err := dbmap.Select(&response.AcceptedTerms, query)
What should I set the type to be for decimal? I want the user to be able to post decimals e.g. 10.44 or 12.00 etc rather than "10.44" or "12.00". I also want the value to be returned as above rather than as a string.
Update
I tried to do this to my Struct but it's still not displaying as 2 decimal places
type AcceptedTerms struct {
Id int64
FirstName string
LastName string
Fee Number
Date *time.Time
}
type Number float64
func (n Number) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%.2f", n)), nil
}
Thanks
Does float32
pose any problems? Since MySQL uses 32 bits to store DECIMAL
, float32
should be good enough.
For scanning MySQL values to Go vars the good practice is to use sql.Null... types. Especially when column is nullable.
For decimals it can be sql.NullFloat64:
// ...
var dec sql.NullFloat64
row.Scan(&dec)
// dec.Valid - bool
// dec.Float64 - float64