Converting a string to a number
-
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?
Thanks,
-Joe Lertola
_______________________________________________
cocoa-dev mailing list | <cocoa-dev...>
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored. -
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?
No offense, but I must call "RTFM" on this one:
<http://developer.apple.com/documentation/Cocoa/Reference/Foundation/
ObjC_classic/Classes/NSString.html#//apple_ref/doc/uid/20000154/
doubleValue>
Nick Zitzmann
<http://www.chronosnet.com/>
_______________________________________________
cocoa-dev mailing list | <cocoa-dev...>
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored. -
/*
To: Joe Lertola <joe...>
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
<tombernard...>
_______________________________________________
cocoa-dev mailing list | <cocoa-dev...>
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.


