Skip to content

Instantly share code, notes, and snippets.

@kasimok
Created March 7, 2017 08:05
Show Gist options
  • Save kasimok/e953af4d4ab646f333a4617ff43a0cc6 to your computer and use it in GitHub Desktop.
Save kasimok/e953af4d4ab646f333a4617ff43a0cc6 to your computer and use it in GitHub Desktop.
get human readable disk size in swift.
/**
* Get the human readable size String according to total bytes.
*/
func uInt64ToHumanReadable(input: Int64, bBinary: Bool) -> String! {
let unit:Int64 = bBinary ? 1024 : 1000;
if input < unit { return String(describing: input)+" B"; }
let exp:Int = Int(log(Double(input)) / log(Double(unit)));
let units: String = (bBinary ? "KMGTPE": "kMGTPE");
let startIndex = units.index(units.startIndex, offsetBy: exp-1);
let endIndex = units.index(units.startIndex, offsetBy: exp-1);
let str = units[startIndex...endIndex]+(bBinary ? "i": "");
return String(format: "%.2f %@B", Double(input) / pow(Double(unit), Double(exp)), str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment