1
|
|
|
package internal |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"math" |
5
|
|
|
"reflect" |
6
|
|
|
"strconv" |
7
|
|
|
|
8
|
|
|
"github.com/gotilty/gotil/internal/errs" |
9
|
|
|
) |
10
|
|
|
|
11
|
|
|
//ToFloat64 returns float64(0) with an error if the parameter is unsupported type. |
12
|
|
|
//Just works with all primitive types. |
13
|
|
|
func ToFloat64(a interface{}) (float64, error) { |
14
|
|
|
val := reflect.ValueOf(a) |
15
|
|
|
switch val.Kind() { |
16
|
|
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
17
|
|
|
return fromInt64ToFloat64(val.Int()) |
18
|
|
|
case reflect.Float32, reflect.Float64: |
19
|
|
|
return fromFloat64ToFloat64(val.Float()) |
20
|
|
|
case reflect.String: |
21
|
|
|
return fromStringToFloat64(val.String()) |
22
|
|
|
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: |
23
|
|
|
return fromUint64ToFloat64(val.Uint()) |
24
|
|
|
case reflect.Bool: |
25
|
|
|
return fromBoolToFloat64(val.Bool()) |
26
|
|
|
default: |
27
|
|
|
if a == nil { |
28
|
|
|
return 0, nil |
29
|
|
|
} |
30
|
|
|
return 0, errs.Int64Error(val.Kind().String()) |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
func fromInt64ToFloat64(s int64) (float64, error) { |
35
|
|
|
var maxInt64 int64 = math.MaxInt64 |
36
|
|
|
if s > maxInt64 { |
37
|
|
|
return 0, errs.CustomError("The entered number cannot be greater than max float64.") |
38
|
|
|
} |
39
|
|
|
return float64(s), nil |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
func fromFloat64ToFloat64(s float64) (float64, error) { |
43
|
|
|
var maxFloat float64 = math.MaxFloat64 |
44
|
|
|
if s > float64(maxFloat) { |
45
|
|
|
return 0, errs.CustomError("the entered number cannot be greater than max float64.") |
46
|
|
|
} |
47
|
|
|
return float64(s), nil |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
func fromStringToFloat64(s string) (float64, error) { |
51
|
|
|
if s == "" { |
52
|
|
|
return 0, nil |
53
|
|
|
} |
54
|
|
|
d, err := strconv.ParseFloat(s, 64) |
55
|
|
|
if err == nil { |
56
|
|
|
return float64(d), nil |
57
|
|
|
} |
58
|
|
|
return 0, err |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
func fromUint64ToFloat64(s uint64) (float64, error) { |
62
|
|
|
var maxFloat float64 = math.MaxFloat64 |
63
|
|
|
if s > uint64(maxFloat) { |
64
|
|
|
return 0, errs.CustomError("The entered number cannot be greater than max float64.") |
65
|
|
|
} |
66
|
|
|
return float64(s), nil |
67
|
|
|
} |
68
|
|
|
func fromBoolToFloat64(s bool) (float64, error) { |
69
|
|
|
if s { |
70
|
|
|
return 1, nil |
71
|
|
|
} else { |
72
|
|
|
return 0, nil |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|