swiftcode
swiftcode

Reputation: 3059

How to check if input is double or string in Objective-C?

How do you check if a given input is a string or a double? I tried doing [self.display.text doubleValue] and if that's not a valid double, it returns 0, but the problem is that 0 is actually a valid input for an actual double, so the program won't know if it's the default error fallback or an actual valid input.

How do you go around this?

Upvotes: 1

Views: 1925

Answers (3)

N_A
N_A

Reputation: 19897

-[NSFormatter getObjectValue:forString:range:error:] does what you want.

More details here.

Upvotes: 2

atastrophic
atastrophic

Reputation: 3143

You might use Regular Expressions and NSPredicate to test if it is a double value.

NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES '^[-+]?[0-9]*\.?[0-9]+$'"];
BOOL result = [predicate evaluateWithObject:@"yourdoublevaluehere"];

You might need to adjust the Regular expression as I wroteit off the top of my head.

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

Do it the 'C' way using strtod (reference) as that provides you with the last character parsed:

NSString *input = @"123.456";
char *endptr;
double value = strtod([input UTF8String], &endptr);
if (*endptr != '\0')
{
    NSLog(@"input is a string");
}

Upvotes: 1

Related Questions