TWcode
TWcode

Reputation: 823

Receiving an error message within a UITextField

I'm getting a message "NAN" within the UITextField when i'm trying to calculate the percentage of two UITextFields. My current code is as follows:

float firstFloat = [self.tex15.text floatValue]; 
float secondFloat = [self.tex16.text floatValue]; 
float answer = secondFloat / firstFloat * 100;
self.tex20.text = [NSString stringWithFormat:@"%.1f%%",answer];

Upvotes: 0

Views: 182

Answers (2)

csano
csano

Reputation: 13716

I strongly suspect it's an issue with your IBOutlet connections. The following code works fine for me:

@interface testViewController : UIViewController {
    UITextField *tf1;
    UITextField *tf2;
    UILabel *result;
}

@end

@implementation testViewController

- (void)dealloc{
    [tf1 release];
    [tf2 release];
    [result release];
    [super dealloc];
}

-(void) click:(id) obj {
    float firstFloat = [tf1.text floatValue]; 
    float secondFloat = [tf2.text floatValue]; 
    float answer = secondFloat / firstFloat * 100;
    result.text = [NSString stringWithFormat:@"%.1f%%",answer];
}

-(void) viewWillAppear:(BOOL)animated {

    tf1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 30)];
    tf1.backgroundColor = [UIColor whiteColor];

    tf2 = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 200, 30)];
    tf2.backgroundColor = [UIColor whiteColor];

    result = [[UILabel alloc]initWithFrame:CGRectMake(10, 90, 200, 30)];
    result.backgroundColor = [UIColor whiteColor];

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(10, 130, 50, 30);
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

    [self.view addSubview:tf1];
    [self.view addSubview:tf2];
    [self.view addSubview:result];

}

@end

Upvotes: 0

Jim
Jim

Reputation: 73966

NaN means Not a Number. It indicates that your calculation does not result in a valid number. My first guess would be that firstFloat is 0, meaning you are attempting to divide by zero. In turn, this may be caused by self.tex15 being nil - check that your IBOutlet is connected properly.

Upvotes: 1

Related Questions