Last active
September 5, 2019 11:37
-
-
Save phileggel/1b559c50539bd94e3369 to your computer and use it in GitHub Desktop.
Converting Int bytes info to user-friendly String
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
// | |
// 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