Skip to content

Instantly share code, notes, and snippets.

@mminer
Last active April 19, 2023 00:59
Show Gist options
  • Save mminer/d0a043b0b6054f428a8ed1f505bfe1b0 to your computer and use it in GitHub Desktop.
Save mminer/d0a043b0b6054f428a8ed1f505bfe1b0 to your computer and use it in GitHub Desktop.
Formats bytes into a more human-readable form (e.g. MB).
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)"
}
@snoozemoose
Copy link

snoozemoose commented Nov 6, 2018

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.

@flying-sausages
Copy link

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

@mminer
Copy link
Author

mminer commented Nov 7, 2020

@flying-sausages: I'm glad that you found it useful. Making it into an extension is a smart idea.

@kmi4k4k
Copy link

kmi4k4k commented Apr 18, 2023

let k: Double = 1000

Why k is 1000, not 1024?..

@mminer
Copy link
Author

mminer commented Apr 19, 2023

@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