Search code examples
iosobjective-cnsarray

How to find greatest numeric value in Array of string in objective-c?


I have an array of strings

NSArray *myNumbers = @[@"0.0454", @"-1.3534", @"0.345",
                             @"65", @"-0.345", @"1.35"];

How can I find the greatest numeric value (65) from this array of string?

Is there any default method or workaround for this?


Solution

  • Just sort it while converting to float, then get the first or last value depends on your sort

    NSString *max = [myNumbers sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            float first = [(NSString*)a floatValue];
            float second = [(NSString*)b floatValue];
            if (first > second)
                return NSOrderedAscending;
            else if (first < second)
                return NSOrderedDescending;
            return NSOrderedSame;
        }][0];
    

    or

    NSString *max = [[myNumbers sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            return [(NSString *)a compare:(NSString *)b options:NSNumericSearch];
        }] lastObject];