35

How to check if the content of a NSString is an integer value? Is there any readily available way?

There got to be some better way then doing something like this:

- (BOOL)isInteger:(NSString *)toCheck {
  if([toCheck intValue] != 0) {
    return true;
  } else if([toCheck isEqualToString:@"0"]) {
    return true;
  } else {
    return false;
  }
}
Carlos Barbosa
  • 3,083
  • 5
  • 30
  • 30

5 Answers5

82

You could use the -intValue or -integerValue methods. Returns zero if the string doesn't start with an integer, which is a bit of a shame as zero is a valid value for an integer.

A better option might be to use [NSScanner scanInt:] which returns a BOOL indicating whether or not it found a suitable value.

Pang
  • 9,564
  • 146
  • 81
  • 122
Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
  • 23
    Right on! A simple [[NSScanner scannerWithString:value] scanInt:nil] will check if "value" has an integer value. Thanks! – Carlos Barbosa Feb 19 '09 at 18:38
  • What value will integerValue return if the string is empty? – A Salcedo Jul 03 '12 at 14:18
  • @ASalcedo Presumably you can't rely on the contents if the method returns NO. – Stephen Darlington Jul 03 '12 at 14:54
  • 6
    Note `-[NSScanner scanInt:]` returns true for @"00ab" as well -- use `-[NSScanner isAtEnd]` from Steven Green's answer below, or convert into NSNumber (http://stackoverflow.com/questions/1448804/how-to-convert-an-nsstring-into-an-nsnumber?rq=1) to handle such cases – Vivek Jul 13 '13 at 01:12
45

Something like this:

NSScanner* scan = [NSScanner scannerWithString:toCheck]; 
int val; 
return [scan scanInt:&val] && [scan isAtEnd];
Steven Green
  • 981
  • 8
  • 15
8

Building on an answer from @kevbo, this will check for integers >= 0:

if (fooString.length <= 0 || [fooString rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound) {
    NSLog(@"This is not a positive integer");
}

A swift version of the above:

func getPositive(incoming: String) -> String {
    if (incoming.characters.count <= 0) || (incoming.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil) {
        return "This is NOT a positive integer"
    }
    return "YES! +ve integer"
}
Community
  • 1
  • 1
coco
  • 2,998
  • 1
  • 35
  • 58
2

Do not forget numbers with decimal point!!!

NSMutableCharacterSet *carSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"0123456789."];
BOOL isNumber = [[subBoldText stringByTrimmingCharactersInSet:carSet] isEqualToString:@""];
TtheTank
  • 332
  • 3
  • 8
0
func getPositive(input: String) -> String {
    if (input.count <= 0) || (input.rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) != nil) {
        return "This is NOT a positive integer"
    }
    return "YES! integer"
}

Update @coco's answer for Swift 5

black_pearl
  • 2,549
  • 1
  • 23
  • 36