# Converting a NSString to a float



## <Jacob> (Jan 29, 2006)

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?


----------



## ksv (Jan 30, 2006)

<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?




```
NSString *string = @"0.5";
float result = 0.3 + [string floatValue];
```


----------



## <Jacob> (Jan 30, 2006)

I already had something similar to yourcode.  But I copied yours and the result came out to be this:1072273817.00.


----------



## ksv (Jan 31, 2006)

<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?


```
NSLog( "%f", result );
```


----------



## <Jacob> (Jan 31, 2006)

Yes, I am doing that.  It still comes up with the same number.
I'm running Mac OS 10.2.8


----------



## boyfarrell (Jan 31, 2006)

Have you tried using printf on the float?


----------



## <Jacob> (Feb 1, 2006)

No, but I think using a NSTextView or a NSLog is the same.


----------



## boyfarrell (Feb 1, 2006)

```
#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".


----------



## <Jacob> (Feb 2, 2006)

That works for me too, I think what I was doing wrong was displaying it with a %d.


----------



## boyfarrell (Feb 2, 2006)

Congratulations!

Yeah that would make sense actual, thought I'd seen this problem before. 

So what you programming?


----------



## <Jacob> (Feb 2, 2006)

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).


----------

