1

i want to sum to values which i get from a textfiel. how can i cast a textfield value in double value ?

Regards Caglar

user389431
  • 109
  • 1
  • 3
  • 12
  • There are no casts from Objective-C objects to primitive types, so it's not what you're looking for. – zneak Sep 16 '10 at 19:47

3 Answers3

3

See this question: How to do string conversions in Objective-C?

double myDouble = [myTextField.text doubleValue];
Community
  • 1
  • 1
AlcubierreDrive
  • 3,654
  • 2
  • 29
  • 45
  • thank u. i checked your link. but they sum integer values. How can i sum double values ? – user389431 Sep 16 '10 at 19:55
  • In your view controller, have a double property for the sum, like "@property (assign) double sum;". In your init method, set "self.sum = 0.0;". Then, to sum values as they are inputted, you would probably have a button that the user presses after entering each number. That button should trigger a method (via an IBAction if you're using a nib) that will do "self.sum = self.sum + [myTextField.text doubleValue];" and it should also clear the text field, like " myTextField.text = @""; " – AlcubierreDrive Sep 16 '10 at 20:21
  • And of course you can also reset "self.sum = 0.0;" whenever appropriate, such as when the user presses a "Reset" button – AlcubierreDrive Sep 16 '10 at 20:24
2

You can use doubleValue to convert a NSString (from your text field) to a double like so:

double myDouble = [myTextField.text doubleValue]; 

This isn't a cast, by the way, it's a conversion. The doubleValue method performs a conversion from a string to a double representation. Casts are something you can only perform on primitive numeric types or pointers in Objective-C.

LBushkin
  • 129,300
  • 32
  • 216
  • 265
1

convert text entered in textfield to integer

double mydouble=[_myTextfield.text doubleValue];

rounding to the nearest double

mydouble=(round(mydouble));

rounding to the nearest int(considering only positive values)

int myint=(int)(mydouble);

converting from double to string

myLabel.text=[NSString stringWithFormat:@"%f",mydouble];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];

converting from int to string

myLabel.text=[NSString stringWithFormat:@"%d",myint];

or

NSString *mystring=[NSString stringWithFormat:@"%f",mydouble];
Ashish P
  • 1,463
  • 1
  • 20
  • 29