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

前端 未结 8 1866
被撕碎了的回忆
被撕碎了的回忆 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:06

    NSString *stringFromFileSize(NSInteger theSize)
    {
        /*
         From http://snippets.dzone.com/posts/show/3038 with slight modification
         */
        float floatSize = theSize;
        if (theSize<1023)
            return([NSString stringWithFormat:@"%i bytes",theSize]);
        floatSize = floatSize / 1024;
        if (floatSize<1023)
            return([NSString stringWithFormat:@"%1.1f KB",floatSize]);
        floatSize = floatSize / 1024;
        if (floatSize<1023)
            return([NSString stringWithFormat:@"%1.1f MB",floatSize]);
        floatSize = floatSize / 1024;
    
        return([NSString stringWithFormat:@"%1.1f GB",floatSize]);
    }
    

提交回复
热议问题