switch to SI standard and add test

This commit is contained in:
Victor Vieux 2013-05-23 10:29:09 +00:00
parent ed56b6a905
commit b45143da9b
2 changed files with 17 additions and 5 deletions

View File

@ -133,20 +133,19 @@ func HumanDuration(d time.Duration) string {
}
// HumanSize returns a human-readable approximation of a size
// (eg. "44kB", "17MB")
// using SI standard (eg. "44kB", "17MB")
func HumanSize(size int64) string {
i := 0
var sizef float64
sizef = float64(size)
units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
for sizef > 1024.0 {
sizef = sizef / 1024.0
for sizef >= 1000.0 {
sizef = sizef / 1000.0
i++
}
return fmt.Sprintf("%.*f %s", i, sizef, units[i])
return fmt.Sprintf("%.4g %s", sizef, units[i])
}
func Trunc(s string, maxlen int) string {
if len(s) <= maxlen {
return s

View File

@ -261,3 +261,16 @@ func TestCompareKernelVersion(t *testing.T) {
&KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "0"},
-1)
}
func TestHumanSize(t *testing.T) {
size1000 := HumanSize(1000)
if size1000 != "1 kB" {
t.Errorf("1000 -> expected 1 kB, got %s", size1000)
}
size1024 := HumanSize(1024)
if size1024 != "1.024 kB" {
t.Errorf("1024 -> expected 1.024 kB, got %s", size1024)
}
}