Re: Converting a string to a number
Re: Converting a string to a number
- Subject: Re: Converting a string to a number
- From: Tom Bernard <email@hidden>
- Date: Wed, 24 Mar 2004 02:04:18 -0700
/*
To: Joe Lertola <email@hidden>
On Mar 23, 2004, at 4:10 PM, Joe Lertola wrote:
> If I have a NSString that contains a number how can I convert it into
> a real number. For example if I have a NSString = "123.456 is my
> number", how can I get the value 123.456 into a float?
*/
NSString *myString = @"123.456 is my number";
float myNumber = [myString floatValue];
The debugger shows myNumber set to 123.456001
Does that work for you? Note that the string must start with the number.
NSString *myString = @"embedded number 123.456 is my number";
float myNumber = [myString floatValue];
yields myNumber set to 0.
For embedded numbers, use an NSScanner.
BOOL numberScanned, garbageScanned;
NSScanner *myScanner = [NSScanner scannerWithString:myString];
garbageScanned = [myScanner scanUpToCharactersFromSet:[NSCharacterSet
characterSetWithCharactersInString:@".0123456789"] intoString:nil];
numberScanned = [myScanner scanFloat:&myNumber];
Tom Bernard
email@hidden
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.