format.go 321 B

1234567891011121314151617
  1. package common
  2. import (
  3. "fmt"
  4. )
  5. func FormatTraffic(trafficBytes int64) string {
  6. units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
  7. unitIndex := 0
  8. size := float64(trafficBytes)
  9. for size >= 1024 && unitIndex < len(units)-1 {
  10. size /= 1024
  11. unitIndex++
  12. }
  13. return fmt.Sprintf("%.2f%s", size, units[unitIndex])
  14. }