Skip to content

Instantly share code, notes, and snippets.

@victorchee
Last active August 29, 2015 14:21
Show Gist options
  • Save victorchee/d47c62ae0fa5c1105bd2 to your computer and use it in GitHub Desktop.
Save victorchee/d47c62ae0fa5c1105bd2 to your computer and use it in GitHub Desktop.
Binary unit transform
typedef NS_ENUM(NSUInteger, BinaryUnit) {
b,
B,
KB,
MB,
GB,
TB,
PB,
ZB,
YB
};
+ (NSString*)binaryUnitTranform:(double)value withUnit:(BinaryUnit)unit;
+ (NSString*)binaryUnitTranform:(double)value withUnit:(BinaryUnit)unit
{
if (value < 1.0 && value > 0 && unit > b) {
return [self binaryUnitTranform:value*1024.0 withUnit:--unit];
} else if (value > 1024.0 && unit < YB) {
return [self binaryUnitTranform:value/1024.0 withUnit:++unit];
} else {
NSDictionary *units = @{@(b):@"b",
@(B):@"B",
@(KB):@"KB",
@(MB):@"MB",
@(GB):@"GB",
@(TB):@"TB",
@(PB):@"PB",
@(ZB):@"ZB",
@(YB):@"YB"};
return [NSString stringWithFormat:@"%.2f%@", value, units[@(unit)]];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment