Skip to content

Instantly share code, notes, and snippets.

@fdstevex
Last active December 18, 2015 13:39
Show Gist options
  • Save fdstevex/5791889 to your computer and use it in GitHub Desktop.
Save fdstevex/5791889 to your computer and use it in GitHub Desktop.
This is an Objective-C function that will parse a float from a string where the fractional part is expressed as numerator/denominator. So, for example, it will parse "1 1/2", or "3/4".
/**
* Turn a string like "1 1/2" into 1.5. If there is no fractional
* part, then the whole number is returned. If the number is not
* well formatted, then nil is returned.
*/
+ (NSNumber *)numberFromFractionalString:(NSString *)string
{
if (string == nil) {
return nil;
}
NSArray *parts = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (parts.count == 0) {
return nil;
}
NSString *wholePart = [parts objectAtIndex:0];
NSString *fractionalPart;
if ([wholePart rangeOfString:@"/"].location != NSNotFound) {
fractionalPart = wholePart;
wholePart = nil;
} else {
if (parts.count == 2) {
fractionalPart = [parts objectAtIndex:1];
}
}
float value = 0.0;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
if (wholePart != nil) {
NSNumber *number = [formatter numberFromString:wholePart];
if (number == nil) {
return nil;
}
value = [wholePart floatValue];
}
if (fractionalPart != nil) {
// Fractional value: "1 1/2" or "2 3/4"
NSArray *fractionParts = [fractionalPart componentsSeparatedByString:@"/"];
if (fractionParts.count == 2) {
NSNumber *numerator = [formatter numberFromString:[fractionParts objectAtIndex:0]];
NSNumber *denominator = [formatter numberFromString:[fractionParts objectAtIndex:1]];
if (numerator == nil || denominator == nil || denominator.integerValue == 0) {
return nil;
}
value = value + (numerator.floatValue / denominator.floatValue);
}
}
return [NSNumber numberWithFloat:value];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment