bytes.go 741 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package bytes
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. // Format formats bytes to string with decimal prefix. For example, 1000 would returns
  7. // 1 KB
  8. func Format(b uint64) string {
  9. return format(float64(b), false)
  10. }
  11. // FormatB formats bytes to string with binary prefix. For example, 1024 would
  12. // return 1 KiB.
  13. func FormatB(b uint64) string {
  14. return format(float64(b), true)
  15. }
  16. func format(b float64, bin bool) string {
  17. unit := float64(1000)
  18. if bin {
  19. unit = 1024
  20. }
  21. if b < unit {
  22. return fmt.Sprintf("%.0f B", b)
  23. } else {
  24. x := math.Floor(math.Log(b) / math.Log(unit))
  25. pre := make([]byte, 1, 2)
  26. pre[0] = "KMGTPE"[uint8(x)-1]
  27. if bin {
  28. pre = pre[:2]
  29. pre[1] = 'i'
  30. }
  31. return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, x), pre)
  32. }
  33. }