How to check if NSString is contains a numeric value?

前端 未结 7 1973
走了就别回头了
走了就别回头了 2021-01-31 09:09

I have a string that is being generate from a formula, however I only want to use the string as long as all of its characters are numeric, if not that I want to do something dif

相关标签:
7条回答
  • 2021-01-31 09:47

    For simple numbers like "12234" or "231231.23123" the answer can be simple.

    There is a transformation law for int numbers: when string with integer transforms to int (or long) number and then, again, transforms it back to another string these strings will be equal.

    In Objective C it will looks like:

    NSString *numStr=@"1234",*num2Str=nil;
    num2Str=[NSString stringWithFormat:@"%lld",numStr.longlongValue];
    
    if([numStr isEqualToString: num2Str]) NSLog(@"numStr is an integer number!");
    

    By using this transformation law we can create solution
    to detect double or long numbers:

    NSString *numStr=@"12134.343"
    NSArray *numList=[numStr componentsSeparatedByString:@"."];
    
    if([[NSString stringWithFormat:@"%lld", numStr.longLongValue] isEqualToString:numStr]) NSLog(@"numStr is an integer number"); 
    else 
    if( numList.count==2 &&
                   [[NSString stringWithFormat:@"%lld",((NSString*)numList[0]).longLongValue] isEqualToString:(NSString*)numList[0]] &&
                   [[NSString stringWithFormat:@"%lld",((NSString*)numList[1]).longLongValue] isEqualToString:(NSString*)numList[1]] )
                NSLog(@"numStr is a double number");
    else 
    NSLog(@"numStr is not a number");
    

    I did not copy the code above from my work code so can be some mistakes, but I think the main point is clear. Of course this solution doesn't work with numbers like "1E100", as well it doesn't take in account size of integer and fractional part. By using the law described above you can do whatever number detection you need.

    0 讨论(0)
提交回复
热议问题