How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Swift

1 Answer

0 votes
import Foundation

class FormatBytesToKilobytesMegabytesGigabytesTerabytes_Swift {
    static func main() {
        print(formatBytes(9823453784599))
        print(formatBytes(7124362542))
        print(formatBytes(23746178))
        print(formatBytes(1048576))
        print(formatBytes(1024000))
        print(formatBytes(873445))
        print(formatBytes(1024))
        print(formatBytes(978))
        print(formatBytes(13))
        print(formatBytes(0))
    }
    
    private static func formatBytes(_ bytes: Int64) -> String {
        let sizes = ["B", "KB", "MB", "GB", "TB"]
        var i = 0
        var dblByte = Double(bytes)
        
        while i < sizes.count - 1 && dblByte >= 1024 {
            dblByte /= 1024
            i += 1
        }
        
        return String(format: "%.2f %@", dblByte, sizes[i])
    }
}

FormatBytesToKilobytesMegabytesGigabytesTerabytes_Swift.main()



/*
run:

8.93 TB
6.64 GB
22.65 MB
1.00 MB
1000.00 KB
852.97 KB
1.00 KB
978.00 B
13.00 B
0.00 B

*/

 



answered Nov 24, 2024 by avibootz
...