-
Notifications
You must be signed in to change notification settings - Fork 1
/
numparse.go
57 lines (51 loc) · 1003 Bytes
/
numparse.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
47
48
49
50
51
52
53
54
55
56
57
package utils
import (
"reflect"
"strconv"
)
// NumParse parses a string to a number type.
func NumParse[T WholeNumber](str string) (T, error) {
bits := 64
signed := true
switch reflect.TypeOf(T(0)).Kind() {
case reflect.Uint8:
signed = false
fallthrough
case reflect.Int8:
bits = 8
case reflect.Uint16:
signed = false
fallthrough
case reflect.Int16:
bits = 16
case reflect.Uint32:
signed = false
fallthrough
case reflect.Int32:
bits = 32
case reflect.Uint64:
signed = false
}
// signed
if signed {
num, parseErr := strconv.ParseInt(str, 10, bits)
if parseErr != nil {
return 0, parseErr
}
return T(num), nil
}
// unsigned
num, parseErr := strconv.ParseUint(str, 10, bits)
if parseErr != nil {
return 0, parseErr
}
return T(num), nil
}
// FloatParse parses a string to a float type.
func FloatParse[T Float](str string) (T, error) {
f, parseErr := strconv.ParseFloat(str, 64)
if parseErr != nil {
return 0, parseErr
}
return T(f), nil
}