2

So i'm creating an API and I needed to store the price of something.

I'm using gorm and gormigrate for my database migration. I'm just wondering what proper type should I use for storing decimals. I've red somewhere that I shouldn't use floats when storing currencies.

type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price <what type should be here> `json:"price"`
}
5
  • I have used github.com/shopspring/decimal for money values. Commented Jun 16, 2018 at 15:04
  • can you please show an example of how you used it? gorm is throwing an error when i do automigrate Commented Jun 16, 2018 at 15:30
  • Sorry, I don't use grom myself and thus don't have any experience using shopspring/decimal with it... Commented Jun 16, 2018 at 15:46
  • @ain, oh, btw thanks for suggesting the package. greatly appreciated! Commented Jun 16, 2018 at 15:47
  • @ain, nice package! Thanks Commented Jun 16, 2018 at 15:56

1 Answer 1

7

So, based on the suggestion of @ain, I used shopspring/decimal. But it's giving me an error when I do automigrate.

It turns out that I only needed to set the type to numeric using a gorm tag to make it work:

type MyStruct struct {
    Name        string `json:"name" gorm:"not null"`
    Description string `json:"description" gorm:"null"`
    Price decimal.Decimal `json:"price" gorm:"type:numeric"`
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.