0

swift 怎样讲byte转换为"K", "M", "G" 等可读的模式

heloise created at6 years ago view count: 318

比如1024byte转换为1KB, 1024MB转换为1GB这种可读性更高的表达方式。

report
回复
3

public func sizeString(size: UInt64) -> String {

    let units: [String] = ["bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]

    var size = size
    for i in 0..<units.count-1 {
        if size < 1000 {
            return "\(size) \(units[i])"
        }
        if size < 1024 * 10 {
            let tmp = round((Double(size) * 10.0) / 1024.0) / 10.0
            let fmt = (tmp < 10.0) ? "%0.1f" : "%0.0f"
            let num = String(format: fmt, tmp)
            return "\(num) \(units[i+1])"
        }

        size /= 1024
    }

    return "\(size) YB"
}
6 years ago 回复

相关搜索关键词