-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_to_float.go
More file actions
64 lines (60 loc) · 1.16 KB
/
convert_to_float.go
File metadata and controls
64 lines (60 loc) · 1.16 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package u
import (
"encoding/binary"
"math"
"regexp"
"strconv"
"strings"
)
// ToFloat32 to float32
func ToFloat32(val interface{}) float32 {
return float32(ToFloat64(val))
}
// ToFloat64 to float64
func ToFloat64(val interface{}) float64 {
switch v := val.(type) {
case string:
str := val.(string)
matched, _ := regexp.MatchString(`^[0-9.]+$`, str)
if !matched {
return 0
}
if strings.Count(val.(string), ".") <= 1 {
floatVal, err := strconv.ParseFloat(str, 64)
if err != nil {
return 0
}
return floatVal
}
return 0
case int:
return float64(val.(int))
case int8:
return float64(val.(int8))
case int16:
return float64(val.(int16))
case int32:
return float64(val.(int32))
case int64:
return float64(val.(int64))
case uint:
return float64(val.(uint))
case uint8:
return float64(val.(uint8))
case uint16:
return float64(val.(uint16))
case uint32:
return float64(val.(uint32))
case uint64:
return float64(val.(int64))
case float32:
return float64(val.(float32))
case float64:
return v
case []byte:
bits := binary.LittleEndian.Uint64(val.([]byte))
return math.Float64frombits(bits)
default:
return 0
}
}