ObjC/Cocoa class for converting size to human-readable string?

前端 未结 8 1868
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 05:41

Is there a simple way to do something like..

[NSMagicDataConverter humanStringWithBytes:20000000]

..which would return \"19.1MB\"?

8条回答
  •  北海茫月
    2020-11-28 06:25

    I know the questions is for Obj C but if anyone looking for a swift version:

     public static func fileSizeDisplay(fromBytes:Int) -> String {
            let display = ["bytes","KB","MB","GB","TB","PB"]
            var value:Double = Double(fromBytes)
            var type = 0
            while (value > 1024){
                value /= 1024
                type = type + 1
    
            }
            return "\(String(format:"%g", value)) \(display[type])"
    
        }
    

提交回复
热议问题