Does GORM have a Decimal datatype?
Solution 1
Michael's answer works. But If you want to use decimal type with golang, you can use shopspring/decimal like this:
type TableName struct {
Amount decimal.Decimal `json:"amount" sql:"type:decimal(20,8);"`
}
Solution 2
If you're using AutoMigrate, you can give GORM SQL instructions (in your struct model) on how to build the table. Try something like the following:
type Product struct {
Id int
ProductName string `sql:"type:varchar(250);"`
Amount float32 `sql:"type:decimal(10,2);"`
}
Solution 3
I know this is a little old but I had this issue and it's very hard to find the answer. if you're using Gorm with liquibase use BigDecimal for any floating point numbers.
Solution 4
This one works for me:
type Product struct {
decimal.Decimal `gorm:"type:decimal(7,6);"`
}
I was also trying the suggested sql:
but columns end up as text
fields in sqlite3 when using gorm's AutoMigrate()
.
Martin Thoma
I also have a blog about Code, the Web and Cyberculture (medium as well) and a career profile on Stackoverflow. My interests are mainly machine-learning, neural-networks, data-analysis, python, and in general backend development. I love building secure and maintainable systems.
Updated on August 16, 2022Comments
-
Martin Thoma almost 2 years
Does GORM have a decimal datatype to store money values (->
Decimal(8,2)
)?I could not find it on https://github.com/jinzhu/gorm#define-models-structs