简体   繁体   中英

“isnan” doesn't seem to work

Simply trying to catch non numeric input Read MANY items . Tried decimalDigitCharacterSet (found it hard to believe that something that starts with the word "decimal" doesn't contain a decimal). Tried mutable character set to add the decimal. Been working to include "10.5" with "96" and still exclude "abc".

the following code produces "IS a number" no matter what I put in textbox1

double whatTheHey;

whatTheHey = _textBox1.text.doubleValue;

if isnan(whatTheHey) {
    _textBox2.text = @"NOT a number > ";
}

if (!isnan(whatTheHey)) {
    _textBox2.text = @"IS a number > ";
}

10.5 , 99 , qwerty all yield "IS a number"

This seems like a heck of a lot of work just to catch non numeric input.

Does anybody have any blatantky simple examples of working code to catch non numeric but accept numbers with decimal in them?

NaN does not literally mean "anything that is not a number". It is the name of a specific value — namely one floats can have after certain indeterminate operations such as dividing zero by zero or taking the square root of a negative number. See the Wikipedia entry for more history.

To actually parse the numeric value of a string, you probably want to look into NSNumberFormatter :

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *a = [numberFormatter numberFromString:@"10.5"];
NSNumber *b = [numberFormatter numberFromString:@"96"];
NSNumber *c = [numberFormatter numberFromString:@"abc"];
NSLog(@"a: %@, b: %@, c: %@", a, b, c);

Yields: a: 10.5, b: 96, c: (null)

A simpler (if less flexible) solution that meets your specific criteria might be:

BOOL isNumber(NSString *aString){
  return [aString integerValue] || [aString floatValue];
}

But if you're writing for iOS (or OS X), you really ought to get comfortable with the NSFormatter s. They'll make your life a lot easier.

Try this. I think it should do what you need:

- (BOOL)isStringNumeric:(NSString *)input {
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    NSNumber *number = [numberFormatter numberFromString:input];
    return (number != nil);
}

to check wether a string is numeric or not use the following piece of code.

    NSString *newString = @"11111";
    NSNumberFormatter *nf = [NSNumberFormatter new];
    BOOL isDecimal = [nf numberFromString:newString] != nil;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM