generated from atomicgo/template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
to.go
86 lines (74 loc) · 1.57 KB
/
to.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package utils
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"atomicgo.dev/constraints"
)
// ToJSON converts the given value to a JSON string.
func ToJSON(v any) (string, error) {
r, err := json.Marshal(v)
if err != nil {
return "", fmt.Errorf("could not marshal json: %w", err)
}
return string(r), nil
}
func ToPrettyJSON(v any, indent ...string) (string, error) {
if len(indent) == 0 {
indent = append(indent, " ")
}
r, err := json.MarshalIndent(v, "", indent[0])
if err != nil {
return "", fmt.Errorf("could not marshal json: %w", err)
}
return string(r), nil
}
// ToString converts the given value to a string.
func ToString(v any) string {
return fmt.Sprint(v)
}
// ToInt converts the given value to an int.
// If the value is a float, it will be rounded to the nearest integer. (Rounds up if the decimal is 0.5 or higher)
func ToInt[T string | constraints.Number](value T) int {
switch value := any(value).(type) {
case int:
return value
case int8:
return int(value)
case int16:
return int(value)
case int32:
return int(value)
case int64:
return int(value)
case uint:
return int(value)
case uint8:
return int(value)
case uint16:
return int(value)
case uint32:
return int(value)
case uint64:
return int(value)
case float32:
value += 0.5
return int(value)
case float64:
value += 0.5
return int(value)
case string:
var i int
if !strings.Contains(value, ".") {
i, _ = strconv.Atoi(value)
} else {
f, _ := strconv.ParseFloat(value, 64)
f += 0.5 // Round up
i = int(f)
}
return i
default:
return 0
}
}