FormatSize formats a byte count using binary units (B, KB, MB, GB, TB, PB). Values below a kilobyte are shown as whole bytes; larger values are shown with one decimal place of precision.
(n int64)
| 179 | // Values below a kilobyte are shown as whole bytes; larger values are shown with |
| 180 | // one decimal place of precision. |
| 181 | func FormatSize(n int64) string { |
| 182 | const unit = 1024 |
| 183 | if n < unit { |
| 184 | return fmt.Sprintf("%d B", n) |
| 185 | } |
| 186 | |
| 187 | units := []string{"KB", "MB", "GB", "TB", "PB"} |
| 188 | |
| 189 | // Stop at the largest known unit so an out-of-range index can never occur, |
| 190 | // even for byte counts beyond a petabyte. |
| 191 | div, exp := int64(unit), 0 |
| 192 | for v := n / unit; v >= unit && exp < len(units)-1; v /= unit { |
| 193 | div *= unit |
| 194 | exp++ |
| 195 | } |
| 196 | |
| 197 | value := float64(n) / float64(div) |
| 198 | return fmt.Sprintf("%.1f %s", value, units[exp]) |
| 199 | } |
no outgoing calls