mirror of
https://github.com/json-iterator/go.git
synced 2025-02-01 19:14:29 +02:00
#68 string to float64
This commit is contained in:
parent
2ea4d48e1f
commit
086001225d
@ -15,6 +15,7 @@ const MinInt = -MaxInt - 1
|
||||
func RegisterFuzzyDecoders() {
|
||||
jsoniter.RegisterTypeDecoder("string", &FuzzyStringDecoder{})
|
||||
jsoniter.RegisterTypeDecoder("float32", &FuzzyFloat32Decoder{})
|
||||
jsoniter.RegisterTypeDecoder("float64", &FuzzyFloat64Decoder{})
|
||||
jsoniter.RegisterTypeDecoder("int", &FuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||
if isFloat {
|
||||
val := iter.ReadFloat64()
|
||||
@ -201,3 +202,25 @@ func (decoder *FuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.It
|
||||
iter.ReportError("FuzzyFloat32Decoder", "not number or string")
|
||||
}
|
||||
}
|
||||
|
||||
type FuzzyFloat64Decoder struct {
|
||||
}
|
||||
|
||||
func (decoder *FuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
||||
valueType := iter.WhatIsNext()
|
||||
var str string
|
||||
switch valueType {
|
||||
case jsoniter.Number:
|
||||
*((*float64)(ptr)) = iter.ReadFloat64()
|
||||
case jsoniter.String:
|
||||
str = iter.ReadString()
|
||||
newIter := iter.Config().BorrowIterator([]byte(str))
|
||||
defer iter.Config().ReturnIterator(newIter)
|
||||
*((*float64)(ptr)) = newIter.ReadFloat64()
|
||||
if newIter.Error != nil {
|
||||
iter.Error = newIter.Error
|
||||
}
|
||||
default:
|
||||
iter.ReportError("FuzzyFloat32Decoder", "not number or string")
|
||||
}
|
||||
}
|
||||
|
@ -71,3 +71,17 @@ func Test_float_to_float32(t *testing.T) {
|
||||
should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
|
||||
should.Equal(float32(1.23), val)
|
||||
}
|
||||
|
||||
func Test_string_to_float64(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val float64
|
||||
should.Nil(jsoniter.UnmarshalFromString(`"100"`, &val))
|
||||
should.Equal(float64(100), val)
|
||||
}
|
||||
|
||||
func Test_float_to_float64(t *testing.T) {
|
||||
should := require.New(t)
|
||||
var val float64
|
||||
should.Nil(jsoniter.UnmarshalFromString(`1.23`, &val))
|
||||
should.Equal(float64(1.23), val)
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user