GORM是否有Decimal数据类型?

huangapple go评论110阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年3月11日 18:21:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/28983956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定