What's weird about floats in objective-c?

Aright, what’s up with this? This code using a double works just fine:
[objc]
double myDouble = 2.2;
NSLog(@"myDouble %f", myDouble);

[self testDouble:myDouble];

- (void) testDouble:(double)myDouble {
NSLog(@"testDouble %f", myDouble);
}
[/objc]

This code prints:
myDouble 2.200000
testDouble 2.200000

No surprises there. But the same code using a float behaves very strangely:
[objc]
float myFloat = 3.3;
NSLog(@"myFloat %f", myFloat);

[self testFloat:myFloat];

- (void) testFloat:(float)myFloat {
NSLog(@"testFloat %f", myFloat);
}
[/objc]

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:

[objc]
float myFloat = 3.3;
[/objc]

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:
[objc]
float myFloat = 3.3f;
[/objc]

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:
[objc]
[self testFloat:3.3f];
[/objc]

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?

One Comment

  1. youminbuluo
    Posted January 30, 2011 at 5:10 am | Permalink

    the same here!
    I encountered the problem when I used CGFloat!

Post a Comment

Your email is never shared. Required fields are marked *

*
*