Preface
When you are developing a project, you may encounter a requirement that we may only enter a pure number. At this time, we must filter and judge the string, and prompt the operation if it does not meet the pure number, so as to achieve the best interactive effect and meet the needs.
The following are several ways to determine whether a string is a pure number
The first way is to use NSScanner:
1. Plastic surgery judgment
- (BOOL)isPureInt:(NSString *)string{ NSScanner* scan = [NSScanner scannerWithString:string]; int val; return [scan scanInt:&val] && [scan isAtEnd]; }
2. Floating point shape judgment:
- (BOOL)isPureFloat:(NSString *)string{ NSScanner* scan = [NSScanner scannerWithString:string]; float val; return [scan scanFloat:&val] && [scan isAtEnd]; }
The second method is to use loop 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 a common method in C language.
- (BOOL)isAllNum:(NSString *)string{ unichar c; for (int i=0; i<; i++) { c=[string characterAtIndex:i]; if (!isdigit(c)) { return NO; } } return YES; }
The third method is to use the trimming method of NSString
- (BOOL)isPureNumandCharacters:(NSString *)string { string = [string stringByTrimmingCharactersInSet;[NSCharacterSet decimalDigitCharacterSet]]; if( > 0) { return NO; } return YES; }
Summarize
The above are three functions that can help you determine whether a string is a number. There is no direct method in iOS to determine whether it is a number, so you can only add methods to implement it yourself. I hope that the several methods summarized in this article can help you. If you have any questions, you can leave a message to communicate.