Martin Thoma
Martin Thoma

Reputation: 136635

Does GORM have a Decimal datatype?

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

Upvotes: 13

Views: 22449

Answers (5)

Zippp
Zippp

Reputation: 458

I know the question is pretty old, and the answers show all the iterations on this problem through the versions of gorm. Still, the solution is not that obvious. This worked for me:

type Product struct {
    ID int
    Price float32 `gorm:"type:numeric(8,2);not null"`
}

Upvotes: 0

Simon
Simon

Reputation: 383

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().

Upvotes: 12

Shinji Yamada
Shinji Yamada

Reputation: 424

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);"`
}

Upvotes: 25

Ethan Davis
Ethan Davis

Reputation: 123

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.

Upvotes: 5

Michael Babcock
Michael Babcock

Reputation: 703

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);"` 
}

Upvotes: 7

Related Questions