Marko Zadravec
Marko Zadravec

Reputation: 8738

Is value of NSString a NSInteger value in iOS

I am interesting of determine if text in NSString is int value or not.

For example :

NSString value = @"something";
int i = value.intValue;
// i -> 0

So i is 0 and it don't give me information if text is real int value.

Second problem is if string is int alike :

NSString vaue = @"10.10.21.32"
int i = value.intValue;
// i -> 10

How to determinate if text is real int value ?

Marko

Upvotes: 0

Views: 201

Answers (2)

pbasdf
pbasdf

Reputation: 21536

Use NSNumberFormatter, with lenient set to false and allowsFloats set to false.

NSNumberFormatter *intFormat = [NSNumberFormatter alloc] init];
intFormat.lenient = false;
intFormat.allowsFloats = false;
NSNumber *myNumber = [intFormat numberFromString:value];
int finalValue;
if (myNumber) { // was able to parse OK
    finalValue = [myNumber intValue];
} else {
    // handle invalid strings here
}

Upvotes: 1

Mehul Patel
Mehul Patel

Reputation: 23053

I did sort of code. It will use to recognise that string is text, real or int.

#define REGEX_NUMBER @"^[0-9.0-9]*$"

NSString *digitString = @"test";

NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", REGEX_NUMBER];

BOOL isNumber = [phoneTest evaluateWithObject:digitString];

if (isNumber) {

    // String contains digit characters

    if ([digitString rangeOfString:@"."].location == NSNotFound) {

        // String contains real value
        int value = [digitString intValue];

    } else {

        // String contains int value
        double value = [digitString doubleValue];

    }
} else {
    NSLog(@"alpha-numeric value");
    // String contains alpha-numeric values.
}

Upvotes: 0

Related Questions