bytes.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. KibiByte = Byte * 1024
  13. MebiByte = KibiByte * 1024
  14. GibiByte = MebiByte * 1024
  15. )
  16. func HumanBytes(b int64) string {
  17. var value float64
  18. var unit string
  19. switch {
  20. case b >= TeraByte:
  21. value = float64(b) / TeraByte
  22. unit = "TB"
  23. case b >= GigaByte:
  24. value = float64(b) / GigaByte
  25. unit = "GB"
  26. case b >= MegaByte:
  27. value = float64(b) / MegaByte
  28. unit = "MB"
  29. case b >= KiloByte:
  30. value = float64(b) / KiloByte
  31. unit = "KB"
  32. default:
  33. return fmt.Sprintf("%d B", b)
  34. }
  35. switch {
  36. case value >= 100:
  37. return fmt.Sprintf("%d %s", int(value), unit)
  38. case value >= 10:
  39. return fmt.Sprintf("%d %s", int(value), unit)
  40. case value != math.Trunc(value):
  41. return fmt.Sprintf("%.1f %s", value, unit)
  42. default:
  43. return fmt.Sprintf("%d %s", int(value), unit)
  44. }
  45. }
  46. func HumanBytes2(b uint64) string {
  47. switch {
  48. case b >= GibiByte:
  49. return fmt.Sprintf("%.1f GiB", float64(b)/GibiByte)
  50. case b >= MebiByte:
  51. return fmt.Sprintf("%.1f MiB", float64(b)/MebiByte)
  52. case b >= KibiByte:
  53. return fmt.Sprintf("%.1f KiB", float64(b)/KibiByte)
  54. default:
  55. return fmt.Sprintf("%d B", b)
  56. }
  57. }