Converting a NSString to a float

<Jacob>

Registered
I've been trying to convert a NSString to a float and I can't make it work. I've already tried doing these:
float aFloat=[aString floatValue];
float aFloat=float(aString);

If you would, could you post some code that will do it?
 
<Jacob> said:
I've been trying to convert a NSString to a float and I can't make it work. I've already tried doing these:
float aFloat=[aString floatValue];
float aFloat=float(aString);

If you would, could you post some code that will do it?

Code:
NSString *string = @"0.5";
float result = 0.3 + [string floatValue];
 
I already had something similar to yourcode. But I copied yours and the result came out to be this:1072273817.00.
 
<Jacob> said:
I already had something similar to yourcode. But I copied yours and the result came out to be this:1072273817.00.

Are you displaying the result correctly?

Code:
NSLog( "%f", result );
 
Code:
#import <stdio.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>

int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	NSString *string = @"0.5";
	float result = 0.3 + [string floatValue];
	printf("\nresult = %f\n",result);
     NSLog(@"%f", result );

[pool release];

    return 0;
}

//result = 0.800000
//2006-02-01 19:25:05.760 Dynamic[3484] 0.800000

Works fine for me....

Remeber NSLog takes an NSString arguments @"like this" not char "like this".
 
I'm programming a time converter/calculator. I have many other things that I'm working on (all of them needed to convert a string to a float).
 
Back
Top