本文介绍了Golang-从MySQL存储/检索小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用gin gonic框架,并已构建了JSON API.

I am using the gin gonic framework and have built a JSON API.

我有一个新的端点要输入,但是其中一个值是小数.我创建了以下结构:

I have a new end point I want to make but one of the values is a decimal. I created the following struct:

type AcceptedTerms struct {
    Id          int64
    FirstName   string
    LastName    string
    Fee         ***DECIMAL***
    Date        *time.Time
}

我的控制器代码段:

    query = "SELECT " +
            "AcceptedTerms.* " +
            "FROM AcceptedTerms " +
            "ORDER BY " + sort_by + " " + order_by +
            " LIMIT " + limit2 +
            " OFFSET " + offset2`

_, err := dbmap.Select(&response.AcceptedTerms, query)

我应该设置小数的类型是什么?我希望用户能够发布小数,例如10.44或12.00等,而不是"10.44"或"12.00".我还希望按上述方式而不是字符串返回值.

What should I set the type to be for decimal? I want the user to be able to post decimals e.g. 10.44 or 12.00 etc rather than "10.44" or "12.00". I also want the value to be returned as above rather than as a string.

更新

我尝试对我的Struct执行此操作,但它仍未显示为小数点后两位

I tried to do this to my Struct but it's still not displaying as 2 decimal places

type AcceptedTerms struct {
    Id          int64
    FirstName   string
    LastName    string
    Fee         Number
    Date        *time.Time
}

type Number float64

func (n Number) MarshalJSON() ([]byte, error) {
    return []byte(fmt.Sprintf("%.2f", n)), nil
}

谢谢

推荐答案

对于将MySQL值扫描到Go var中,好的做法是使用sql.Null ...类型.尤其是当column为空时.

For scanning MySQL values to Go vars the good practice is to use sql.Null... types. Especially when column is nullable.

对于小数,它可以是sql.NullFloat64:

For decimals it can be sql.NullFloat64:

// ...
var dec sql.NullFloat64
row.Scan(&dec)
// dec.Valid - bool
// dec.Float64 - float64

这篇关于Golang-从MySQL存储/检索小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:15