In a textfield I should write a number: this number can be with point (10.23) or without poin (10); but I should to check that this number is a number and not a word. Can I开发者_JAVA百科 check if in a textfield there is a number instead a word? Example: if I write a word instead a number I want an nslog that say that there is an error.
Another way:
NSString *string = @"684.14";
NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet];
BOOL stringIsValid = ([[string stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@""] ||
[[string stringByTrimmingCharactersInSet:decimalSet] isEqualToString:@"."]);
Also remember that you can use textField.keyboardType = UIKeyboardTypeNumberPad;
for the keyboard. (This won't guarantee only numeric entries, however, it's just about user friendliness.)
Check out NSScanner
: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003726
if( [[NSScanner scannerWithString:@"-123.4e5"] scanFloat:NULL] )
NSLog( @"\"-123.4e5\" is numeric" );
else
NSLog( @"\"-123.4e5\" is not numeric" );
if( [[NSScanner scannerWithString:@"Not a number"] scanFloat:NULL] )
NSLog( @"\"Not a number\" is numeric" );
else
NSLog( @"\"Not a number\" is not numeric" );
// prints: "-123.4e5" is numeric
// prints: "Not a number" is not numeric
精彩评论