Skip to content

Instantly share code, notes, and snippets.

@fethica
Last active January 9, 2024 15:42
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fethica/52ef6d842604e416ccd57780c6dd28e6 to your computer and use it in GitHub Desktop.
Save fethica/52ef6d842604e416ccd57780c6dd28e6 to your computer and use it in GitHub Desktop.
[Swift] Convert Bytes to Kilobytes to Megabytes to Gigabytes
public struct Units {
public let bytes: Int64
public var kilobytes: Double {
return Double(bytes) / 1_024
}
public var megabytes: Double {
return kilobytes / 1_024
}
public var gigabytes: Double {
return megabytes / 1_024
}
public init(bytes: Int64) {
self.bytes = bytes
}
public func getReadableUnit() -> String {
switch bytes {
case 0..<1_024:
return "\(bytes) bytes"
case 1_024..<(1_024 * 1_024):
return "\(String(format: "%.2f", kilobytes)) kb"
case 1_024..<(1_024 * 1_024 * 1_024):
return "\(String(format: "%.2f", megabytes)) mb"
case (1_024 * 1_024 * 1_024)...Int64.max:
return "\(String(format: "%.2f", gigabytes)) gb"
default:
return "\(bytes) bytes"
}
}
}
print(Units(bytes: 546546546).getReadableUnit())
@jbarros35
Copy link

Thats a very good script. Thank you.

@anjannath
Copy link

Thanks mate!

@pkrll
Copy link

pkrll commented Jan 24, 2020

Nice! But have you checked out ByteCountFormatter?

@hrieke
Copy link

hrieke commented Mar 19, 2020

License?

@mcstrassell09
Copy link

Awesome! thanks!

@norrisboat
Copy link

Thanks

@bobgodwinx
Copy link

bobgodwinx commented Nov 17, 2022

let formatted = ByteCountFormatter.string(fromByteCount: (1024 * 1024 * 8), countStyle: .file)

prints 8.4 MB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment