From 3721714f009bafe0576c2066e6fea1ee42b57b74 Mon Sep 17 00:00:00 2001 From: c9s Date: Sat, 24 Oct 2020 18:21:43 +0800 Subject: [PATCH] Support json unmarshaller for fixedpoint --- pkg/fixedpoint/convert.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/pkg/fixedpoint/convert.go b/pkg/fixedpoint/convert.go index b7fd3e9e7..8d065288c 100644 --- a/pkg/fixedpoint/convert.go +++ b/pkg/fixedpoint/convert.go @@ -1,8 +1,11 @@ package fixedpoint import ( + "encoding/json" "math" "strconv" + + "github.com/pkg/errors" ) const DefaultPrecision = 8 @@ -39,6 +42,33 @@ func (v Value) Add(v2 Value) Value { return Value(int64(v) + int64(v2)) } +func (v *Value) UnmarshalJSON(data []byte) error { + var a interface{} + var err = json.Unmarshal(data, &a) + if err != nil { + return err + } + + switch d := a.(type) { + case float64: + *v = NewFromFloat(d) + + case float32: + *v = NewFromFloat32(d) + + case int: + *v = NewFromInt(d) + case int64: + *v = NewFromInt64(d) + + default: + return errors.Errorf("unsupported type: %T %v", d, d) + + } + + return nil +} + func NewFromString(input string) (Value, error) { v, err := strconv.ParseFloat(input, 64) if err != nil { @@ -52,6 +82,10 @@ func NewFromFloat(val float64) Value { return Value(int64(math.Round(val * DefaultPow))) } +func NewFromFloat32(val float32) Value { + return Value(int64(math.Round(float64(val) * DefaultPow))) +} + func NewFromInt(val int) Value { return Value(int64(val * DefaultPow)) }