eff_bytesize.go 906 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. import "fmt"
  6. type ByteSize float64
  7. const (
  8. _ = iota // ignore first value by assigning to blank identifier
  9. KB ByteSize = 1 << (10 * iota)
  10. MB
  11. GB
  12. TB
  13. PB
  14. EB
  15. ZB
  16. YB
  17. )
  18. func (b ByteSize) String() string {
  19. switch {
  20. case b >= YB:
  21. return fmt.Sprintf("%.2fYB", b/YB)
  22. case b >= ZB:
  23. return fmt.Sprintf("%.2fZB", b/ZB)
  24. case b >= EB:
  25. return fmt.Sprintf("%.2fEB", b/EB)
  26. case b >= PB:
  27. return fmt.Sprintf("%.2fPB", b/PB)
  28. case b >= TB:
  29. return fmt.Sprintf("%.2fTB", b/TB)
  30. case b >= GB:
  31. return fmt.Sprintf("%.2fGB", b/GB)
  32. case b >= MB:
  33. return fmt.Sprintf("%.2fMB", b/MB)
  34. case b >= KB:
  35. return fmt.Sprintf("%.2fKB", b/KB)
  36. }
  37. return fmt.Sprintf("%.2fB", b)
  38. }
  39. func main() {
  40. fmt.Println(YB, ByteSize(1e13))
  41. }