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)
| 154 | // Values below a kilobyte are shown as whole bytes; larger values are shown with |
| 155 | // one decimal place of precision. |
| 156 | func FormatSize(n int64) string { |
| 157 | const unit = 1024 |
| 158 | if n < unit { |
| 159 | return fmt.Sprintf("%d B", n) |
| 160 | } |
| 161 | |
| 162 | units := []string{"KB", "MB", "GB", "TB", "PB"} |
| 163 | |
| 164 | // Stop at the largest known unit so an out-of-range index can never occur, |
| 165 | // even for byte counts beyond a petabyte. |
| 166 | div, exp := int64(unit), 0 |
| 167 | for v := n / unit; v >= unit && exp < len(units)-1; v /= unit { |
| 168 | div *= unit |
| 169 | exp++ |
| 170 | } |
| 171 | |
| 172 | value := float64(n) / float64(div) |
| 173 | return fmt.Sprintf("%.1f %s", value, units[exp]) |
| 174 | } |
no outgoing calls