Henry David
Henry David

Reputation: 441

Objective C - iOS - verify float/double

I am working on the infamous Stanford calculator assignment. I need to verify inputted numbers for valid float values, so we can handle numbers like 102.3.79.

To avoid having to write a little loop to count periods in the string, there's got to be a built-in function yeah?

Upvotes: 2

Views: 2262

Answers (4)

Jano
Jano

Reputation: 63707

-(BOOL) isNumeric:(NSString*)string {    
    NSNumberFormatter *formatter = [NSNumberFormatter new];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *number = [formatter numberFromString:string];
    [formatter release]; // if using ARC remove this line
    return number!=nil;
}

-(BOOL) isFloat:(NSString*)string {
    NSScanner *scanner = [NSScanner scannerWithString:string];
    [scanner scanFloat:NULL];
    return [scanner isAtEnd];
}

Upvotes: 2

Khaled Barazi
Khaled Barazi

Reputation: 8741

Having gone through CS193P, I think the idea is to get comfortable with NSString and UILabel versus using C. I would look into having a simple decimal point BOOL flag, as buttons are pressed and you are concatenating the numbers 1- for use and 2- for display.

This will come in handy as well when you are doing other checks like hanging decimal points at the end of the number or allowing the user to backspace a number.

Edited for example:

Create an IBAction connected to each number button:

- (IBAction)numberButtonPressed:(UIButton *)sender 
{  
  if([sender.titleLabel.text isEqualToString:@"."])
  {
    if (!self.inTheMiddleOfEnteringANumber)
        self.display.text=[NSString stringWithString:@"0."];

    else if (!self.decimalPointEntered)
      {
        self.display.text=[self.display.text stringByAppendingString:sender.titleLabel.text]; 
        self.decimalPointEntered=TRUE;
      }
   }   
self.inTheMiddleOfEnteringANumber=TRUE;
}

Upvotes: 2

wxactly
wxactly

Reputation: 2470

There's at least one fairly elegant solution for counting @"." in a string:

NSString *input = @"102.3.79";
if([[input componentsSeparatedByString:@"."] count] > 2) {
    NSLog(@"input has too many points!");
}

Digging a little deeper... If you're looking to validate the whole string as a number, try configuring an NSNumberFormatter and call numberFromString: (NSNumberFormatter documentation).

Upvotes: 2

user529758
user529758

Reputation:

You can use the C standard library function strtod(). It stops where it encounters an error, and sets its output argument accordingly. You can exploit this fact as follows:

- (BOOL)isValidFloatString:(NSString *)str
{
    const char *s = str.UTF8String;
    char *end;
    strtod(s, &end);
    return !end[0];
}

Upvotes: 8

Related Questions