Skip to content

How to work with exact decimal types?

go-jet edited this page May 18, 2021 · 1 revision

Exact decimal types (DECIMAL and NUMERIC) are by default converted to float64. This can lead to loss of precision during query result mapping. Currently it's not possible to customize generated model types. This feature will be added later.
But it is possible to create custom model type, and even to combine custom with generated model types.

For instance:
Assuming table name is my_table, and my_table has column money of the type NUMERIC.

type MoneyType int64  // or some other type 

func (m *MoneyType) Scan(value interface{}) error {   // value is string 
 ...  add implementation
}

func (m MoneyType) Value() (driver.Value, error) {
 ...  add implementation
}

type MyTable struct {
    model.MyTable
    Money MoneyType       // overwrite just Money field from model.MyTable
}

It is also possible to use some of the third party decimal libraries:

import "github.com/shopspring/decimal"

type MyTable struct {
    model.MyTable
    Money decimal.Decimal  // overwrite just Money field from model.MyTable
}

New MyTable type can now be used in any place model.MyTable is used(as a QueryContext destination or as model for INSERT or UPDATE).