user464193
user464193

Reputation:

iPhone NSString

I just wanted to know how i can determine whether a NSString string has a number.

Upvotes: 0

Views: 206

Answers (3)

Vineet Choudhary
Vineet Choudhary

Reputation: 7632

You can check whether a string has a number or not by using regex

    NSString *search = @"23.3";
    //regex for integer number ->   ^[0-9]*$
    //regex for integer and decimal number ->    ^[0-9]+([\,\.][0-9]+)?$
    NSString *pattern = @"(^[0-9]+([,.][0-9]+)?$)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSTextCheckingResult *match = [regex firstMatchInString:search options:0 range:NSMakeRange(0, search.length)];

    if(match == nil){
        NSLog(@"Not a number");
    }else{
        NSLog(@"Number");
    }

Upvotes: 0

ljkyser
ljkyser

Reputation: 1019

You can use [NSNumberFormatter numberFromString: s]; and it will return nil if it is not a number.

NSString *s = @"2.5";

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * num = [formatter numberFromString:s];
[formatter release];

If num is nil it is not a number.

Link to docs on NSNumberFormatterStyle

Upvotes: 1

kevboh
kevboh

Reputation: 5245

Check out NSNumberFormatter's numberFromString: method.

Upvotes: 0

Related Questions