Skip to content

Instantly share code, notes, and snippets.

@yujinqiu
Forked from mminer/formatBytes.swift
Created September 9, 2020 06:58
Show Gist options
  • Save yujinqiu/4aaffc10e3837960ab46d1a76da9665f to your computer and use it in GitHub Desktop.
Save yujinqiu/4aaffc10e3837960ab46d1a76da9665f 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)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment