-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhumanize.go
78 lines (69 loc) · 1.77 KB
/
humanize.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
package humanize
import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
func Dehumanize(num float64, unit string) (float64, error) {
suffixes := map[string]int{"": 0, "K": 1, "M": 2, "G": 3, "T": 4, "P": 5, "E": 6, "Z": 7}
suffix := "B"
var prefix string
if strings.HasSuffix(unit, suffix) {
prefix = unit[:len(unit)-1]
} else {
prefix = unit
}
prefix = strings.ToUpper(prefix)
if s, ok := suffixes[prefix]; ok {
value := num * math.Pow(1024.0, float64(s))
return value, nil
} else {
return 0.0, fmt.Errorf("Unknown unit: '%s'", prefix)
}
}
func DehumanizeString(value string) (float64, error) {
r, _ := regexp.Compile(`^([0-9.]+)\s*([a-zA-Z]+)$`)
r_simple, _ := regexp.Compile("^([0-9.]+)$")
m := r.FindStringSubmatch(value)
m_simple := r_simple.FindStringSubmatch(value)
if len(m_simple) == 2 {
return strconv.ParseFloat(m_simple[0], 64)
}
if len(m) == 3 {
f, _ := strconv.ParseFloat(m[1], 64)
return Dehumanize(f, m[2])
}
return 0.0, fmt.Errorf("Invalid value: '%s'", value)
}
func Absolutize(value string) (response float64, e error) {
var v string
suffix := "%"
if strings.HasSuffix(value, suffix) {
v = value[:len(value)-1]
} else {
e = fmt.Errorf("Missing percent sign in '%s'", value)
return response, e
}
value_f, err := strconv.ParseFloat(v, 64)
if err != nil {
return response, err
} else {
return value_f / 100.0, nil
}
}
func Humanize(num float64, precision int, suffix string) string {
suffixes := []string{"", "K", "M", "G", "T", "P", "E", "Z"}
if suffix == "" {
suffix = "B"
}
format_str := fmt.Sprintf("%%3.%df%%s%%s", precision)
for _, unit := range suffixes {
if math.Abs(num) < 1024.0 {
return fmt.Sprintf(format_str, num, unit, suffix)
}
num = num / 1024.0
}
return fmt.Sprintf("%.1f%s%s", num, "Yi", suffix)
}