diff --git a/util.go b/util.go index 05aecc6..1c03dfb 100644 --- a/util.go +++ b/util.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "reflect" + "strconv" ) // format bytes number friendly @@ -75,3 +76,16 @@ func CopyStruct(dst interface{}, src interface{}) { } } + +func FormatBytes(bytes int64) string { + const unit = 1024 + if bytes < unit { + return strconv.FormatInt(bytes, 10) + " B" + } + div, exp := int64(unit), 0 + for n := bytes / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.2f%cB", float64(bytes)/float64(div), "KMGTPE"[exp]) +}