Last active
August 29, 2015 14:21
-
-
Save victorchee/d47c62ae0fa5c1105bd2 to your computer and use it in GitHub Desktop.
Binary unit transform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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