bytes.go 752 B

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