views:

4134

answers:

5

HI , i am getting a string input from a UITextField i want to check that this string in numeric . how i will do that .. (numeric can have decimal points also) . how to do that ?

A: 

You can use the doubleValue of your string like

NSString *string=@"1.22";
double a=[string doubleValue];

i think this will return a as 0.0 if the string is invalid (it might throw an exception, in which case you can just catch it, the docs say 0.0 tho). more info here http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSString%5FClass/Reference/NSString.html#//apple%5Fref/occ/instm/NSString/doubleValue

Daniel
Also, using a library function is usually better than rolling your own. In this case, other cultures use a comma for the decimal point, and presumably the Cocoa libs can handle that.
kibibu
+8  A: 

There are a few ways you could do this:

  1. Use NSNumberFormatter's numberFromString: method. This will return an NSNumber if it can parse the string correctly, or nil if it cannot.
  2. Use NSScanner
  3. Strip any non-numeric character and see if the string still matches
  4. Use a regular expression

IMO, using something like -[NSString doubleValue] wouldn't be the best option because both @"0.0" and @"abc" will have a doubleValue of 0. The *value methods all return 0 if they're not able to convert the string properly, so it would be difficult to distinguish between a legitimate string of @"0" and a non-valid string. Something like C's strtol function would have the same issue.

I think using NSNumberFormatter would be the best option, since it takes locale into account (ie, the number @"1,23" in Europe, versus @"1.23" in the USA).

Dave DeLong
Hmmm, I must be setting the options incorrectly for NSNumberFormatter. When I use numberFromString using the string "34jfkjdskj80" it will return the number 3480. It seems to just strip the characters instead of returning nil.
Tony Eichelberger
@Tony yeah I'm not sure what you're doing, because the following logs "N: (null)" for me: `NSNumberFormatter * f = [[NSNumberFormatter alloc] init]; NSNumber * n = [f numberFromString:@"34jfkjdskj80"]; NSLog(@"N: %@", n);`
Dave DeLong
Thank you. I will double check and compare against your code.
Tony Eichelberger
Well, I copied in your example and ran it, now I get "N: 34"? Strange. This is on the iPhone SDK 3.0.1 if that matters.
Tony Eichelberger
@Dave - I think I figured it out. Let me know if this sounds correct. I changed the formatter behavior to NSNumberFormatterBehavior10_0 and now it displays N: (null)
Tony Eichelberger
NOOOOOO! I guess NSNumberFormatterBehavior10_0 is not available on the iphone SDK anymore? I was trying the example in a console app, but lo and behold that constant is not loger recognized for the iphone.
Tony Eichelberger
This is a little old, but in case anybody is reading this, I thought it should be worth noting that an `NSScanner`, like `NSNumberFormatter`, takes locale into account when parsing the string, provided you use `setLocale:` on the scanner object (you could, for example, provide `[NSLocale currentLocale]`).
dreamlax
+4  A: 

I use this code in my Mac app, the same or similar should work with the iPhone. It's based on the RegexKitLite regular expressions and turns the text red when its invalid.

static bool TextIsValidValue( NSString* newText, double &value )
{
    bool result = false;

    if ( [newText isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"] ) {
     result = true;
     value = [newText doubleValue];
    }
    return result;
}

- (IBAction) doTextChanged:(id)sender;
{
    double value;
    if ( TextIsValidValue( [i_pause stringValue], value ) ) {
     [i_pause setTextColor:[NSColor blackColor]];
     // do something with the value
    } else {
     [i_pause setTextColor:[NSColor redColor]];
    }
}
Peter N Lewis
+2  A: 

If you want a user to only be allowed to enter numerals, you can make your ViewController implement part of UITextFieldDelegate and define this method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];

  // The user deleting all input is perfectly acceptable.
  if ([resultingString length] == 0) {
    return true;
  }

  NSInteger holder;

  NSScanner *scan = [NSScanner scannerWithString: resultingString];

  return [scan scanInteger: &holder] && [scan isAtEnd];
}

There are probably more efficient ways, but I find this a pretty convenient way. And the method should be readily adaptable to validating doubles or whatever: just use scanDouble: or similar.

Frank Shearar
A: 

You can do it in a few lines like this:

BOOL valid;

NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];

NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];

valid = [alphaNums isSupersetOfSet:inStringSet];

if (!valid) // 

-- this is for validating input is numeric chars only. Look at the documentation for NSCharacterSet for the other options. You can use characterSetWithCharactersInString to specify any set of valid input characters.

Donal O'Danachair