Skip to content

Instantly share code, notes, and snippets.

@phileggel
Last active September 5, 2019 11:37
Show Gist options
  • Save phileggel/1b559c50539bd94e3369 to your computer and use it in GitHub Desktop.
Save phileggel/1b559c50539bd94e3369 to your computer and use it in GitHub Desktop.
Converting Int bytes info to user-friendly String
//
// From Jody Hagins
// http://stackoverflow.com/questions/10091816/nsfilesystemfreesize-translating-result-into-user-friendly-display-of-mb-gb
//
// Converted to swift by phil on 30/11/2015.
// Copyright © 2015 PhilEagleDev. All rights reserved.
//
func prettyBytes(numBytes: Int) -> String {
let scale: Double = 1024
let abbrevs = [ "EB", "PB", "TB", "GB", "MB", "KB", "Bytes"]
let numAbbrevs = abbrevs.count
let bytes = Double(numBytes)
var maximum = pow(Double(scale), Double(numAbbrevs - 1))
for i in 0..<numAbbrevs {
if bytes > maximum {
return String(format: "%0.2f %@", arguments: [bytes / maximum, abbrevs[i]])
}
maximum /= scale
}
return "\(numBytes) Bytes"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment