bytes.go 858 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package format
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. const (
  7. Byte = 1
  8. KiloByte = Byte * 1000
  9. MegaByte = KiloByte * 1000
  10. GigaByte = MegaByte * 1000
  11. TeraByte = GigaByte * 1000
  12. )
  13. func HumanBytes(b int64) string {
  14. var value float64
  15. var unit string
  16. switch {
  17. case b >= TeraByte:
  18. value = float64(b) / TeraByte
  19. unit = "TB"
  20. case b >= GigaByte:
  21. value = float64(b) / GigaByte
  22. unit = "GB"
  23. case b >= MegaByte:
  24. value = float64(b) / MegaByte
  25. unit = "MB"
  26. case b >= KiloByte:
  27. value = float64(b) / KiloByte
  28. unit = "KB"
  29. default:
  30. return fmt.Sprintf("%d B", b)
  31. }
  32. switch {
  33. case value >= 100:
  34. return fmt.Sprintf("%d %s", int(value), unit)
  35. case value >= 10:
  36. return fmt.Sprintf("%d %s", int(value), unit)
  37. case value != math.Trunc(value):
  38. return fmt.Sprintf("%.1f %s", value, unit)
  39. default:
  40. return fmt.Sprintf("%d %s", int(value), unit)
  41. }
  42. }