21 lines
441 B
Go
21 lines
441 B
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
)
|
|
|
|
// FormatBytes 格式化字节大小为人类可读格式
|
|
// 例如: 1024 → "1.00 KB", 1048576 → "1.00 MB"
|
|
func FormatBytes(bytes uint64) string {
|
|
const unit = 1024
|
|
if bytes < unit {
|
|
return fmt.Sprintf("%d B", bytes)
|
|
}
|
|
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])
|
|
}
|