1

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?

swiftcode
  • 3,009
  • 9
  • 37
  • 64

3 Answers3

2

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

More details here.

Community
  • 1
  • 1
N_A
  • 19,627
  • 4
  • 49
  • 97
1

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");
}
trojanfoe
  • 118,129
  • 19
  • 204
  • 237
1

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.

atastrophic
  • 3,123
  • 3
  • 29
  • 50