-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils_float.go
46 lines (43 loc) · 945 Bytes
/
utils_float.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package glog
import (
"fmt"
"math"
"reflect"
"strconv"
)
var floatType = reflect.TypeOf(float64(0))
var stringType = reflect.TypeOf("")
func GetFloat(val interface{}) (float64, error) {
switch i := val.(type) {
case float64:
return i, nil
case float32:
return float64(i), nil
case int64:
return float64(i), nil
case int32:
return float64(i), nil
case int:
return float64(i), nil
case uint64:
return float64(i), nil
case uint32:
return float64(i), nil
case uint:
return float64(i), nil
case string:
return strconv.ParseFloat(i, 64)
default:
v := reflect.ValueOf(val)
v = reflect.Indirect(v)
if v.Type().ConvertibleTo(floatType) {
fv := v.Convert(floatType)
return fv.Float(), nil
} else if v.Type().ConvertibleTo(stringType) {
sv := v.Convert(stringType)
s := sv.String()
return strconv.ParseFloat(s, 64)
}
return math.NaN(), fmt.Errorf("can't convert %v to float64", v.Type())
}
}