7

The following code will identify if a string is an integer - that is, the string contains only digits. But, I hate this code. What is a better way?

NSString *mightBeAnInteger = fooString;
int intValue = [fooString intValue];
if (intValue > 0
    && [[NSString stringWithFormat:@"%d",intValue] isEqualToString:mightBeAnInteger]) {
  NSLog(@"mightBeAnInteger is an integer");
}
Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116

2 Answers2

22

[fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location == NSNotFound will be YES if the string only has number characters in it.

Note that this doesn't catch negative numbers, so you'll have to add in the negative sign (probably by grabbing a mutableCopy and adding the sign).

kevboh
  • 5,207
  • 5
  • 38
  • 54
  • 1
    Good answer but you can just use the custom NSCharacterSet constructor characterSetWithCharactersInString: passing in 0-9 + "." & "-". – Kendall Helmstetter Gelner Feb 01 '11 at 07:07
  • No period- poster wanted integers. Personally I'd rather add the sign than use the string constructor, but that's just me! – kevboh Feb 01 '11 at 13:08
  • This answer doesn't cover cases like: @"1111-1111" which is not a valid int. It is better to check if [fooString intValue] < 0 instead of just adding - sign. – Yoel Gluschnaider Nov 11 '14 at 16:14
1
-(BOOL) stringIsNumeric:(NSString *) str {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *number = [formatter numberFromString:str];
    [formatter release];
    return !!number; // If the string is not numeric, number will be nil
}

source: Objective c: Check if integer/int/number

Community
  • 1
  • 1
ThE uSeFuL
  • 1,456
  • 1
  • 16
  • 29