forked from dustin/go-humanize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orders.go
92 lines (81 loc) · 1.48 KB
/
orders.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
87
88
89
90
91
92
package humanize
import (
"fmt"
"math"
)
// SI Sizes.
const (
femto = pico / 1000.0
pico = nano / 1000.0
nano = micro / 1000.0
micro = milli / 1000.0
milli = unit / 1000.0
unit = 1.0
kilo = unit * 1000.0
mega = kilo * 1000.0
giga = mega * 1000.0
tera = giga * 1000.0
peta = tera * 1000.0
ecto = peta * 1000.0
)
var ordersSizeTable = map[float64]string{
femto: "f",
pico: "p",
nano: "n",
micro: "µ",
milli: "m",
unit: "",
kilo: "K",
mega: "M",
giga: "G",
tera: "T",
peta: "P",
ecto: "E",
}
var ordersLess = []string{
0: "",
1: "m",
2: "µ",
3: "n",
4: "p",
5: "f",
}
// order = 1.0
// value = 100.0, 0.1
// value 803 should give 803
func fitsOrder(order float64, value float64) bool {
if order == unit && value > 100.0 && value < 1000.0 {
return true
}
if value/10.0 > order {
return false
}
if value*100.0 < order {
return false
}
return true
}
func Orders(s float64) string {
if s == 0.0 {
return "0"
}
value := math.Abs(s)
if value < 1.0 {
value *= 10.0
var order int
for order = 0; value < 1.0 && order < len(ordersLess)-1; value *= 1000.0 {
order++
s *= 1000.0
}
return fmt.Sprintf("%.1f%s", s, ordersLess[order])
}
for order, suffix := range ordersSizeTable {
if fitsOrder(order, value) {
if order == unit && value-math.Floor(value) < 0.0001 {
return fmt.Sprintf("%d", int(s))
}
return fmt.Sprintf("%3.1f%s", s/order, suffix)
}
}
return fmt.Sprintf("%3.1f%s", s/ecto, ordersSizeTable[ecto])
}