bytes.go 546 B

1234567891011121314151617181920212223242526
  1. package format
  2. import "fmt"
  3. const (
  4. Byte = 1
  5. KiloByte = Byte * 1000
  6. MegaByte = KiloByte * 1000
  7. GigaByte = MegaByte * 1000
  8. TeraByte = GigaByte * 1000
  9. )
  10. func HumanBytes(b int64) string {
  11. switch {
  12. case b > TeraByte:
  13. return fmt.Sprintf("%.1f TB", float64(b)/TeraByte)
  14. case b > GigaByte:
  15. return fmt.Sprintf("%.1f GB", float64(b)/GigaByte)
  16. case b > MegaByte:
  17. return fmt.Sprintf("%.1f MB", float64(b)/MegaByte)
  18. case b > KiloByte:
  19. return fmt.Sprintf("%.1f KB", float64(b)/KiloByte)
  20. default:
  21. return fmt.Sprintf("%d B", b)
  22. }
  23. }