16

In objective c, how can i check if a string/NSNumber is an integer or int

Andrew
  • 3,874
  • 5
  • 39
  • 67
Daniel
  • 3,017
  • 12
  • 44
  • 61
  • Please explain more fully what you mean. Both NSString and NSNumber can be converted to int or NSInteger, but neither *is* an int or NSInteger. – Chuck Aug 13 '10 at 04:00
  • Ok sorry, i need to know if a String or Int is an int/integer. See i'm dividing a number by another number, but the number a user puts may not be an int. i need to check if its an int number – Daniel Aug 13 '10 at 04:02

6 Answers6

40

If you're trying to determine whether or not an NSString has a numeric value or not, try using NSNumberFormatter.

-(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
}
jcesarmobile
  • 51,328
  • 11
  • 132
  • 176
Anshu Chimala
  • 2,800
  • 2
  • 23
  • 22
  • 4
    I thought I was the only one who did the !! hack to coerce to boolean. Nice! – Scott Means Oct 10 '11 at 18:38
  • 3
    This question is better than the [approved answer](http://stackoverflow.com/a/3473806/377384) because it gives you a true/false result. The approved answer does not. – lindon fox Apr 16 '13 at 03:28
  • 3
    This is better, because the accepted answer doesn't work as expected if you check a string with letters that starts with number. Example "1234asdf" will return 1234, not 0, this returns NO. And "000" will return 0 and you might think is wrong but it's not – jcesarmobile Jan 22 '14 at 09:11
  • Would this depend on the user's locale? – XMB5 Jul 20 '20 at 04:40
12

You can use the intValue method on NSString:

NSString *myString = @"123";
[myString intValue]; // returns (int)123

Here is the Apple documentation for it - it will return 0 if it's not a valid integer: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/intValue

Hope that helps!

codykrieger
  • 1,750
  • 15
  • 19
  • How can i find if a variable is a string? – Daniel Aug 13 '10 at 04:06
  • As in, you want to check and see if some user input is just a plain old string or a number? Like I said above, intValue returns 0 for when an NSString is not a valid integer. Say you're getting info from a UITextView - [[myTextView text] intValue] would return a valid int if possible, or 0 if it can't be validated as an int. – codykrieger Aug 13 '10 at 04:13
  • Well see the problem is. Sometimes the user will not enter any input. because it is not required. And since i'm using an array and grabbing the object from it. I'm getting *** -[NSCFArray objectAtIndex:]: index (3) beyond bounds (3) i need to check if the array is valid somehow? – Daniel Aug 13 '10 at 04:16
  • 17
    What if the string represents the actual integer value 0? – dreamlax Aug 13 '10 at 04:22
  • Could you maybe post some of your code so we can get a better feel for what's going on? – codykrieger Aug 13 '10 at 04:31
  • @Daniel you could create a notNil helper method and then assign NSNull to your array if a value is nil. like this: -(id)notNil:arg { if (arg == nil) { return [NSNull null]; } else { return arg; } This is working well for me. – jpswain Aug 08 '11 at 02:57
  • You can check if that value is in the array (if you're referring to the index) because it will be between 0 and [array count] -1 – ekinnear Jul 27 '12 at 16:54
  • 12
    Be careful with this. This will only return 0 if the string doesn't begin with an integer value. Something like "123 street" will still return the integer 123. Source: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-intValue – hebime Nov 05 '13 at 23:42
  • Not the best solution. Note that `[@"abc" intValue]` will return `0`. Can lead to confusing results. – aroth Apr 11 '14 at 04:35
  • 1
    I couldn't use this because it didn't work in all cases. – kraftydevil Oct 06 '14 at 23:08
4

I've put this in my category NSString (Util).

- (BOOL) isInt {
    if ([self isEqualToString:@"0"])
        return YES;
    return (self.intValue != 0);
}
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
3

To check if a NSNumber if an integer try:

const char *t = [(NSNumber *)value objCType];
if (strcmp("i", t) == 0); // YES if integer
Kevin Sylvestre
  • 37,288
  • 33
  • 152
  • 232
2

For NSString, if you use intValue/integerValue, there are certain cases which are not handled as it takes into consideration only the beginning the string.

For example @"bl3h" was not considered an integer but @" 3h" gave an output of 3

My solution for NSString:

Use :

NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:strName];

NSCharacterSet *numSet = [NSCharacterSet decimalDigitCharacterSet];

if([numSet isSupersetOfSet: charSet])
{
     // It is an integer (or it contains only digits)
}
Shravya Boggarapu
  • 572
  • 1
  • 7
  • 23
0
if( [(NSString *)someString intValue] )
{ /* Contains an int fosho! */ }

if( [(NSNumber *)someNumber intValue] )
{ /* Contains an int wich is not 0.... :D */ }

You can ofcourse first determine whether its a NSString or NSNumber by using

[Object isKindOfClass:[NSString class]] etc...

– boolValue – charValue – decimalValue – doubleValue – floatValue – intValue – integerValue – longLongValue – longValue – shortValue – unsignedCharValue – unsignedIntegerValue – unsignedIntValue – unsignedLongLongValue – unsignedLongValue – unsignedShortValue

are all methods of NSNumber to get its values. NSString got a few similar ones.

Antwan van Houdt
  • 6,989
  • 1
  • 29
  • 52