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 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)" | |
} |
thanks for these, I took the liberty to fork them and convert them to Extensions, so I can now do nice things like
print(6969696969.stringFileSize) // 6,49 GiB
@flying-sausages: I'm glad that you found it useful. Making it into an extension is a smart idea.
let k: Double = 1000
Why k is 1000, not 1024?..
@kmi4k4k: There's some discussion of when to use 1024 vs. 1000 in the comments of the Stack Overflow answer I linked to.
It's more correct to use the "Kib", etc. abbreviations when using base 1024, because "KB", etc. actually refers to base 1000.
macOS's Get Info window, for example, reports file sizes in base 1000.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great stuff and a joy to read! Before I found this gist I was reading though the source code of ByteCountFormatter.swift which is quite massive for such a task. Your code does everything I need in about 5% of the lines of code in ByteCountFormatter.swift.