英文:
Does GORM have a Decimal datatype?
问题
GORM是否有用于存储货币值的十进制数据类型(例如Decimal(8,2)
)?
我在https://github.com/jinzhu/gorm#define-models-structs上没有找到相关信息。
英文:
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
答案1
得分: 21
Michael的回答是正确的。但是如果你想在Golang中使用decimal类型,你可以像这样使用shopspring/decimal:
type TableName struct {
Amount decimal.Decimal `json:"amount" sql:"type:decimal(20,8);"`
}
英文:
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);"`
}
答案2
得分: 10
这是我适用的一个例子:
type Product struct {
decimal.Decimal `gorm:"type:decimal(7,6);"`
}
当我尝试使用建议的 sql:
时,使用 gorm 的 AutoMigrate()
在 sqlite3 中,列最终变成了 text
字段。
英文:
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()
.
答案3
得分: 7
如果你正在使用AutoMigrate,你可以在你的结构模型中给GORM SQL指令来构建表格。尝试像下面这样的代码:
type Product struct {
Id int
ProductName string `sql:"type:varchar(250);"`
Amount float32 `sql:"type:decimal(10,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);"`
}
答案4
得分: 5
我知道这有点旧了,但我遇到了这个问题,很难找到答案。如果你正在使用Gorm和liquibase,对于任何浮点数,请使用BigDecimal。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论