1
0
mirror of https://github.com/json-iterator/go.git synced 2025-02-19 19:59:49 +02:00

fix float convert

This commit is contained in:
Xargin 2017-07-05 00:23:00 +08:00
parent 3829a470ae
commit 4e65952c09
2 changed files with 36 additions and 8 deletions

View File

@ -119,12 +119,37 @@ func (any *stringAny) ToUint64() uint64 {
}
func (any *stringAny) ToFloat32() float32 {
parsed, _ := strconv.ParseFloat(any.val, 32)
return float32(parsed)
return float32(any.ToFloat64())
}
func (any *stringAny) ToFloat64() float64 {
parsed, _ := strconv.ParseFloat(any.val, 64)
if len(any.val) == 0 {
return 0
}
// first char invalid
if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') {
return 0
}
// extract valid num expression from string
// eg 123true => 123, -12.12xxa => -12.12
endPos := 1
for i := 1; i < len(any.val); i++ {
if any.val[i] == '.' || any.val[i] == 'e' {
endPos = i + 1
continue
}
// end position is the first char which is not digit
if any.val[i] >= '0' && any.val[i] <= '9' {
endPos = i + 1
} else {
endPos = i
break
}
}
parsed, _ := strconv.ParseFloat(any.val[:endPos], 64)
return parsed
}

View File

@ -15,12 +15,15 @@ var floatConvertMap = map[string]float64{
`"false"`: 0,
"123": 123,
`"123true"`: 0,
`"123true"`: 123,
`"+"`: 0,
`"-"`: 0,
`"-123true"`: 0,
"0": 0,
`"0"`: 0,
"-1": -1,
`"-123true"`: -123,
`"-99.9true"`: -99.9,
"0": 0,
`"0"`: 0,
"-1": -1,
"1.1": 1.1,
"0.0": 0,