IOS is a method summary for determining whether a string is pure Numbers

  • 2020-09-28 09:11:22
  • OfStack

preface

When we are developing a project, we may be asked to enter only 1 segment of pure number when we meet the requirement. At this time, we will filter and judge the string, and prompt the operation if it does not conform to pure number, so as to achieve the best interaction effect and meet the requirement.

Here are a few ways to determine if a string is purely numeric

The first way is to use NSScanner:

1. Plastic judgment


- (BOOL)isPureInt:(NSString *)string{
NSScanner* scan = [NSScanner scannerWithString:string]; 
int val; 
return [scan scanInt:&val] && [scan isAtEnd];
}

2. Floating point judgment:


- (BOOL)isPureFloat:(NSString *)string{
NSScanner* scan = [NSScanner scannerWithString:string]; 
float val; 
return [scan scanFloat:&val] && [scan isAtEnd];
}

The second way is to use circular judgment


- (BOOL)isPureNumandCharacters:(NSString *)text 
{ 
  for(int i = 0; i < [text length]; ++i) {
    int a = [text characterAtIndex:i]; 
    if ([self isNum:a]){
      continue; 
    } else { 
      return NO; 
    } 
  } 
  return YES; 
}

Or in C.


- (BOOL)isAllNum:(NSString *)string{
  unichar c;
  for (int i=0; i<string.length; i++) {
    c=[string characterAtIndex:i];
    if (!isdigit(c)) {
      return NO;
    }
  }
  return YES;
}

The third way is to use the trimming method of NSString


- (BOOL)isPureNumandCharacters:(NSString *)string 
{ 
string = [string stringByTrimmingCharactersInSet;[NSCharacterSet decimalDigitCharacterSet]];
if(string.length > 0) 
{
   return NO;
} 
return YES;
}

conclusion

The above are three functions that can help you to determine whether a string is a number. There is no direct method to determine whether a string is a number in iOS, so we can only add methods to achieve it. I hope this article summarizes a few methods to help you, if you have questions can leave a message to communicate.


Related articles: