Decimal type in Go and Postgresql with gorm
In Go, when interacting with the PostgreSQL database using GORM, handling decimal types (typically used for representing monetary values or other data requiring precise decimal representation) is a common requirement. In PostgreSQL, decimal types are typically represented by the or types, which can store exact numerical values and allow specifying precision (total number of digits) and scale (number of digits after the decimal point).In Go, since the language itself does not directly support decimal types, we typically use libraries such as to handle decimal numbers requiring high precision. This library provides a type to support high-precision arithmetic operations.However, to use this type with PostgreSQL's or types in GORM, we need to perform some adaptation to ensure data is correctly transferred between the Go application and the database.ExampleFirst, you need to import the library:Then, define your model. When defining models with GORM, you can directly use the type:In the above code, the field is defined as the type and the corresponding database column type is specified via the tag, meaning this field can store up to 10 digits in total, with 2 digits after the decimal point.Data Reading and WritingNext, when you need to write data to the database or read data from it, GORM and the library work well together without requiring additional data conversion:In the above example, we create a new instance, set the price, and save it to the database. Then, we retrieve the product's information from the database and print the price. During this process, the type seamlessly corresponds with PostgreSQL's type, ensuring data precision.Thus, you can use GORM to handle decimal types in Go and PostgreSQL. This is crucial for applications that need to process financial data or other data requiring high-precision calculations and storage.