-
Notifications
You must be signed in to change notification settings - Fork 315
/
format.go
55 lines (47 loc) · 887 Bytes
/
format.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
package main
import (
"fmt"
)
type units struct {
scale uint64
base string
units []string
}
var (
binaryUnits = &units{
scale: 1024,
base: "",
units: []string{"KB", "MB", "GB", "TB", "PB"},
}
timeUnitsUs = &units{
scale: 1000,
base: "us",
units: []string{"ms", "s"},
}
timeUnitsS = &units{
scale: 60,
base: "s",
units: []string{"m", "h"},
}
)
func formatUnits(n float64, m *units, prec int) string {
amt := n
unit := m.base
scale := float64(m.scale) * 0.85
for i := 0; i < len(m.units) && amt >= scale; i++ {
amt /= float64(m.scale)
unit = m.units[i]
}
return fmt.Sprintf("%.*f%s", prec, amt, unit)
}
func formatBinary(n float64) string {
return formatUnits(n, binaryUnits, 2)
}
func formatTimeUs(n float64) string {
units := timeUnitsUs
if n >= 1000000.0 {
n /= 1000000.0
units = timeUnitsS
}
return formatUnits(n, units, 2)
}