0

I am developing an iOS app and I want to check wether the string in the textfield is a NaN. I am using the following code, I am calling this code inside button click:

int incrby = [self.valueField.text intValue];

if (isnan(incrby)) {
    [[[UIAlertView alloc] initWithTitle:@"" message:@"Enter a valid number for the increment" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    [self.valueField becomeFirstResponder];
    return;
}

But the above code is not working. By not working I mean if I enter a NaN value it does not show alert.

For eg: if I enter hey or hey3 it should show alert

I dont want to make the textfield as number only (show numberpad only).

I searched and found some examples but could not solve my problem

I am new to iOS and don't know what to do what I am doing wrong

Thanks in advance

Larme
  • 24,190
  • 6
  • 51
  • 81
user2413621
  • 2,916
  • 7
  • 24
  • 28
  • 1
    http://stackoverflow.com/questions/565696/nsstring-is-integer ? – Larme May 27 '14 at 10:02
  • An integer value will never (can never) be a NaN as NaN is a floating point concept. See @Larme's comment for some ways to validate numeric input. – David Berry May 27 '14 at 22:14

2 Answers2

0

It's not working as expected, because calling intValue on an NSString with non-numeric characters will return 0 (which is a number).

The following should do the trick:

// Remove any digits from the string to leave only letters & punctuation
NSString *lettersAndPunctuation = [self.valueField.text stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];

// If there are any letters or punctuation, show the alert
if (lettersAndPunctuation.length > 0) {
    // Show alert, etc
    return;
}
Vinny Coyne
  • 2,365
  • 15
  • 24
0

you can check this way

if ([[NSString stringWithFormat:@"%f", output] isEqualToString:@"nan"]) {

}

Banker Mittal
  • 1,918
  • 14
  • 26