bytes.go 1.1 KB

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