-
Notifications
You must be signed in to change notification settings - Fork 0
/
numeric.go
66 lines (59 loc) · 1.78 KB
/
numeric.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
package swissknife
import (
"fmt"
"math"
"strconv"
"strings"
"time"
)
// GetValuePrecision - find out the precision of the numeric value
func GetValuePrecision(val float64) int {
strs := strings.Split(strings.TrimRight(strconv.FormatFloat(val, 'f', 4, 32), "0"), ".")
if len(strs) < 2 {
return 0
}
return len(strs[1])
}
// FloatToString - convert float to string
func FloatToString(val float64) string {
return strconv.FormatFloat(val, 'f', 8, 64)
}
// FormatDuration - format duration 52h -> "2 days 4 hours"
func FormatDuration(duration time.Duration) string {
if duration.Seconds() < 60.0 {
return fmt.Sprintf("%d seconds", int64(duration.Seconds()))
}
if duration.Minutes() < 60.0 {
remainingSeconds := math.Mod(duration.Seconds(), 60)
return fmt.Sprintf("%d minutes %d seconds", int64(duration.Minutes()), int64(remainingSeconds))
}
if duration.Hours() < 24.0 {
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
return fmt.Sprintf("%d hours %d minutes %d seconds",
int64(duration.Hours()), int64(remainingMinutes), int64(remainingSeconds))
}
remainingHours := math.Mod(duration.Hours(), 24)
remainingMinutes := math.Mod(duration.Minutes(), 60)
remainingSeconds := math.Mod(duration.Seconds(), 60)
format := ""
args := []interface{}{}
daysCount := int64(duration.Hours() / 24)
if daysCount > 0 {
format += "%d days"
args = append(args, daysCount)
}
if int64(remainingHours) > 0 {
format += " %d hours"
args = append(args, int64(remainingHours))
}
if int64(remainingMinutes) > 0 {
format += " %d minutes"
args = append(args, int64(remainingMinutes))
}
if int64(remainingSeconds) > 0 {
format += " %d seconds"
args = append(args, int64(remainingSeconds))
}
return fmt.Sprintf(format, args...)
}