-
-
Save yujinqiu/4aaffc10e3837960ab46d1a76da9665f 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