Skip to content

Instantly share code, notes, and snippets.

@flying-sausages
Forked from mminer/formatBytes.swift
Last active November 5, 2020 22:30
Show Gist options
  • Save flying-sausages/518892a52fdf986ea0ea9bf47c3c9f0b to your computer and use it in GitHub Desktop.
Save flying-sausages/518892a52fdf986ea0ea9bf47c3c9f0b to your computer and use it in GitHub Desktop.
Formats bytes into a more human-readable form (e.g. MiB) using Extensions instead of functions
// Forked from https://gist.github.com/mminer/d0a043b0b6054f428a8ed1f505bfe1b0 to
import Foundation
public extension Double {
var stringFileSize: String {
guard self > 0 else {
return "0 bytes"
}
guard self != 1 else {
return "1 byte"
}
// Adapted from http://stackoverflow.com/a/18650828
let suffixes = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
let k: Double = 1024
let i = floor(log(self) / log(k))
// Format number with thousands separator and everything below 1 GB with no decimal places.
let numberFormatter = NumberFormatter()
numberFormatter.maximumFractionDigits = i < 3 ? 0 : 2
numberFormatter.numberStyle = .decimal
let numberString = numberFormatter.string(from: NSNumber(value: self / pow(k, i))) ?? "Unknown"
let suffix = suffixes[Int(i)]
return "\(numberString) \(suffix)"
}
}
public extension Int {
var stringFileSize: String {
return Double(self).stringFileSize
}
}
/////////////////////////
// Does the following:
print(123123123123123.0.stringFileSize) // 111,98 TiB
print(6969696969.stringFileSize) // 6,49 GiB
print(1.0.stringFileSize) // 1 byte
print(1029.stringFileSize) // 1 KiB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment