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

前端 未结 8 1870
被撕碎了的回忆
被撕碎了的回忆 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:20
    - (id)transformedValue:(id)value
    {
    
        double convertedValue = [value doubleValue];
        int multiplyFactor = 0;
    
        NSArray *tokens = @[@"bytes",@"KB",@"MB",@"GB",@"TB"];
    
        while (convertedValue > 1024) {
            convertedValue /= 1024;
            multiplyFactor++;
        }
    
        return [NSString stringWithFormat:@"%4.2f %@",convertedValue, tokens[multiplyFactor]];
    }
    
    0 讨论(0)
  • 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])"
    
        }
    
    0 讨论(0)
提交回复
热议问题