Last active
April 19, 2023 00:59
-
-
Save mminer/d0a043b0b6054f428a8ed1f505bfe1b0 to your computer and use it in GitHub Desktop.
Formats bytes into a more human-readable form (e.g. MB).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func format(bytes: Double) -> String { | |
guard bytes > 0 else { | |
return "0 bytes" | |
} | |
// Adapted from http://stackoverflow.com/a/18650828 | |
let suffixes = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"] | |
let k: Double = 1000 | |
let i = floor(log(bytes) / log(k)) | |
// Format number with thousands separator and everything below 1 GB with no decimal places. | |
let numberFormatter = NumberFormatter() | |
numberFormatter.maximumFractionDigits = i < 3 ? 0 : 1 | |
numberFormatter.numberStyle = .decimal | |
let numberString = numberFormatter.string(from: NSNumber(value: bytes / pow(k, i))) ?? "Unknown" | |
let suffix = suffixes[Int(i)] | |
return "\(numberString) \(suffix)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@kmi4k4k: There's some discussion of when to use 1024 vs. 1000 in the comments of the Stack Overflow answer I linked to.
macOS's Get Info window, for example, reports file sizes in base 1000.