FormatBytes

This commit is contained in:
jiangyong27 2023-12-15 11:50:26 +08:00
parent 4562d6124f
commit 2064d0df6a
1 changed files with 14 additions and 0 deletions

14
util.go
View File

@ -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])
}