ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available: E: Exabyte P: Petabyte T: Terabyte G: Gigabyte M: Megabyte K: Kilobyte B: Byte The unit that results in the smallest number greater than or equal to 1 is always chosen.
(bytes uint64)
| 35 | // |
| 36 | // The unit that results in the smallest number greater than or equal to 1 is always chosen. |
| 37 | func ByteSize(bytes uint64) string { |
| 38 | unit := "" |
| 39 | value := float64(bytes) |
| 40 | |
| 41 | switch { |
| 42 | case bytes >= EXABYTE: |
| 43 | unit = "E" |
| 44 | value = value / EXABYTE |
| 45 | case bytes >= PETABYTE: |
| 46 | unit = "P" |
| 47 | value = value / PETABYTE |
| 48 | case bytes >= TERABYTE: |
| 49 | unit = "T" |
| 50 | value = value / TERABYTE |
| 51 | case bytes >= GIGABYTE: |
| 52 | unit = "G" |
| 53 | value = value / GIGABYTE |
| 54 | case bytes >= MEGABYTE: |
| 55 | unit = "M" |
| 56 | value = value / MEGABYTE |
| 57 | case bytes >= KILOBYTE: |
| 58 | unit = "K" |
| 59 | value = value / KILOBYTE |
| 60 | case bytes >= BYTE: |
| 61 | unit = "B" |
| 62 | case bytes == 0: |
| 63 | return "0B" |
| 64 | } |
| 65 | |
| 66 | result := strconv.FormatFloat(value, 'f', 1, 64) |
| 67 | result = strings.TrimSuffix(result, ".0") |
| 68 | return result + unit |
| 69 | } |
| 70 | |
| 71 | // ToMegabytes parses a string formatted by ByteSize as megabytes. |
| 72 | func ToMegabytes(s string) (uint64, error) { |
no outgoing calls
searching dependent graphs…