String to Double Trouble Shooting
How do I correctly convert 开发者_如何学编程a NSString to a double in xcode 3.2? This is my code(abbreviated), but when I run it, the message says (null). What am I doing wrong? Thanks so much!
@synthesize class1sem1;
-(IBAction)buttonPressed
{
NSString *myString = class1sem1.text;
double myDouble = [myString doubleValue];
NSString *message = [[NSString alloc] initWithFormat:
@"%@", myDouble];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Result" message:message delegate:nil cancelButtonTitle:@"Great!" otherButtonTitles:nil];
[alert show];
[alert release];
[message release];
}
Use %g for your double .. not %@
NSString *message = [[NSString alloc] initWithFormat:
@"%g", myDouble];
You try to display a double as if it were an object. Use this instead:
NSString *message = [[NSString alloc] initWithFormat:
@"%f", myDouble];
// ^ note 'f' instead of '@'
f
means "double precision floating point number", while @
means "Objective-C object". A double
is a double precision floating point number, not an Objective-C object.
精彩评论