objective-cfractionsnsscanner

Detect fraction using NSScanner in Objective-C


I receive some user input in a textbox that can contain numbers or a fraction.

For most numbers, the following method can find an integer. However, if you give it 1/2 it returns 1 and throws out the / and 2

What do I need to do to get it to recognize 1/2 and return .5

Thanks for any suggestions:

-(float) getFloatPartOfString:(NSString*) numstr {
    numstr = @"1/2";
    NSScanner *scanner = [NSScanner scannerWithString:numstr];
    NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
    NSString* numberString;

    // Throw away characters before the first number.
    [scanner scanUpToCharactersFromSet:numbers intoString:NULL];

    // Collect numbers.
    [scanner scanCharactersFromSet:numbers intoString:&numberString];
    float number = numberString.floatValue;
    NSLog(@"1/2 turns into:%f",number);
    return number;
}

Solution

  • Since you need to convert the fraction to a decimal, I would scan the two numbers and the / then you can do the math on the two numbers.

    - (float)getFloatPartOfString:(NSString *)numstr {
        NSScanner *scanner = [NSScanner scannerWithString:numstr];
        int numerator = 0;
        int denominator = 0;
    
        float number = 0;
        if ([scanner scanInt:&numerator]) && [scanner scanString:@"/" intoString:nil] && [scanner scanInt:&denominator] {
            number = (float)numerator / (float)denominator;
        } else {
            NSLog(@"Didn't find integer / integer");
        }
    
        NSLog(@"%@ turns into %f", numstr, number);
    
        return number;
    }
    

    Note - the above is not tested so there may be a mistake. Feel free to edit out any mistakes.