views:

523

answers:

2

Hey Guys ,

I have two text fields in which numbers are inputed as strings. I need to convert the strings to numbers, add them together and then display the result in a 3rd textfield.

I am totally new to iPhone programming .. So please don't be hard on me :P

Ok here is the problem

AdditionViewController.h

#import <UIKit/UIKit.h>

@interface AdditionViewController : UIViewController 
{
    IBOutlet UITextField *Number1;
    IBOutlet UITextField *Number2;
    IBOutlet UITextField *SumAnswer;
}

@property (retain, nonatomic) UITextField *Number1;
@property (retain, nonatomic) UITextField *Number2;
@property (retain, nonatomic) UITextField *SumAnswer;
-(IBAction)buttonPressed1:(id)sender;

@end

AdditionViewController.m

#import "AdditionViewController.h"

    @implementation AdditionViewController
    @synthesize Number1;
    @synthesize Number2;
    @synthesize SumAnswer;


    -(IBAction)buttonPressed1:(id)sender
    {
        SumAnswer.text = Number1.text + Number2.text; 
           // I want the above line to be edited so that I can get the addition
             of both the numbers in the 3rd Text Field 
    }

    -
    -
    -
    -
    -
    @end

I am really new to iPhone programming .. I am trying to understand how NSString can be used here .. But I am finding it a bit complicated .

If someone please tell me what the code should be ... It will be a great help . I have to submit a mini project to my school asap .

Thanking You , int3rc3pt0r

+6  A: 

NSString has method allowing to get numeric value from it (e.g. intValue, floatValue etc) - you can use them to convert string to numbers. To convert numbers to string you can use stringWithFormat: method - the way it takes format specifiers is similar to printf function in c.

-(IBAction)buttonPressed1:(id)sender
{
    // You may also need to check if your string data is a valid number
    int result = [Number1.text intValue] + [Number2.text intValue];
    SumAnswer.text = [NSString stringWithFormat:@"%d", result];
}
Vladimir
You beat me to it.. also check that the boxes and button are linked in interface builder
Mobs
+3  A: 
-(IBAction)buttonPressed1:(id)sender
    {
        double answer = [Number1.text doubleValue] + [Number2.text doubleValue]; 
        SumAnswer.text = [NSString stringWithFormat:@"%f", answer];
    }
kubi
Thankyou so much guys !!!!!!!!!!!!!!!!!From India with love :)
int3rc3pt0r
@ kubi ... when i enter 1.2 in number1 and 0.2 in number2 i get answer as 1.0000 whats going wrong ?
int3rc3pt0r
sorry my bad ..i was taking as intValue instead of doubleValue ..thankx a ton anyway ... thankx again
int3rc3pt0r
because it is formatted as a double number :D you need to declare a NSNumberFormatter if you want to format it in your style. "1.0000" is infact 1, but it is formatted as a double number
sfa