眾所周知,浮點數(shù)是很調(diào)皮的
都誰在說顺又,喜歡技術(shù)八卦的你,不可以錯過
浮點計算引發(fā)的血案
Go如何精確計算小數(shù)-Decimal研究-Tidb MyDecimal問題
而mongodb/mongo-go-driver中的bson.Decimal128
只顧及自家存儲的一畝三分地,看起來干干巴巴赫模、麻麻賴賴…… 大家先不著急盤它,據(jù)說有個俊俏的 github.com/shopspring/decimal狡汉,咱們可以說個媒娄徊。
// 我希望mongo中,讀取數(shù)據(jù)時decimal類型直接解析到decimal.Decimal中
// 寫入時盾戴,又直接把decimal.Decimal放入到mongo的decimal類型中
type Model struct {
// 這個VIP積分非常重要寄锐,弄錯公司就玩完啦~
// 只有他才配的上 decimal.Decimal (狗頭
VIPScore decimal.Decimal `bson:"vip_score"`
}
這回文檔有點不好使啦,只能用google到處搜尖啡,到處搜
package mongo
import (
"fmt"
"reflect"
"github.com/shopspring/decimal"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type Decimal decimal.Decimal
func (d Decimal) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error {
decimalType := reflect.TypeOf(decimal.Decimal{})
if !val.IsValid() || !val.CanSet() || val.Type() != decimalType {
return bsoncodec.ValueDecoderError{
Name: "decimalDecodeValue",
Types: []reflect.Type{decimalType},
Received: val,
}
}
var value decimal.Decimal
switch vr.Type() {
case bsontype.Decimal128:
dec, err := vr.ReadDecimal128()
if err != nil {
return err
}
value, err = decimal.NewFromString(dec.String())
if err != nil {
return err
}
default:
return fmt.Errorf("received invalid BSON type to decode into decimal.Decimal: %s", vr.Type())
}
val.Set(reflect.ValueOf(value))
return nil
}
func (d Decimal) EncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error {
decimalType := reflect.TypeOf(decimal.Decimal{})
if !val.IsValid() || val.Type() != decimalType {
return bsoncodec.ValueEncoderError{
Name: "decimalEncodeValue",
Types: []reflect.Type{decimalType},
Received: val,
}
}
dec := val.Interface().(decimal.Decimal)
dec128, err := primitive.ParseDecimal128(dec.String())
if err != nil {
return err
}
return vw.WriteDecimal128(dec128)
}
然后呢橄仆,需要到ClientOptions
注冊自定義編碼解碼
cli, err := mongo.NewClient(options.Client().ApplyURI("這是個mongoURI連接地址").
SetRegistry(bson.NewRegistryBuilder().
RegisterDecoder(reflect.TypeOf(decimal.Decimal{}), Decimal{}).
RegisterEncoder(reflect.TypeOf(decimal.Decimal{}), Decimal{}).
Build())
if err != nil {
log.Fatal().Err(err).Msg("連接到mongo")
}
大概就是這樣。
另外衅斩,我想幫一個朋友問問mongo的接口怎這么費眼睛呢盆顾?