What’s weird about floats in objective-c?
Aright, what’s up with this? This code using a double works just fine:
1 2 3 4 5 6 7 8 9 |
double myDouble = 2.2;
NSLog(@"myDouble %f", myDouble);
[self testDouble:myDouble];
- (void) testDouble:(double)myDouble {
NSLog(@"testDouble %f", myDouble);
} |
This code prints:
myDouble 2.200000
testDouble 2.200000
No surprises there. But the same code using a float behaves very strangely:
1 2 3 4 5 6 7 8 9 |
float myFloat = 3.3;
NSLog(@"myFloat %f", myFloat);
[self testFloat:myFloat];
- (void) testFloat:(float)myFloat {
NSLog(@"testFloat %f", myFloat);
} |
This code prints
myFloat 3.300000
testFloat 36893488147419103232.000000
So what happens to the float that is passed to the testFloat method? According to this Techtopia article about Objective-C 2.0 Data Types when you create a float like this:
1 2 |
float myFloat = 3.3; |
It is internally stored as a double, which has greater precision. If you actually want to store something as a float you need to append an “f” to the number like this:
1 2 |
float myFloat = 3.3f; |
So I thought perhaps that was the problem - that internally it was represented as a double, so when passed in to a method expecting a float there was a conversion error. But when I modified the code above to include the “f” I get the same result.
I also get the same result when I pass the float in directly to the method like this:
1 2 |
[self testFloat:3.3f]; |
So what the heck is going on here? Why can’t I pass a float to a method? What am I missing? I’ll follow up with a comment when I figure it out, but does anybody know why this is happening?
2 Comments
Did you put a method definition in your header file? Due to the way Obj C messaging works, floats don’t seem to get set properly if the compiler doesn’t know ahead of time (via the header method definition).
Oh, that is probably it then. I wonder what type it thinks it is?