mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-10 09:11:55 +00:00
Support json unmarshaller for fixedpoint
This commit is contained in:
parent
944b673626
commit
3721714f00
|
@ -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))
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user