OUR BLOG

Thoughts on development, design and the world we live in.



What's weird about floats in objective-c?

By admin in Uncategorized. Posted on August 9th

Aright, what’s up with this? This code using a double works just fine:

This code prints:
myDouble 2.200000
testDouble 2.200000

No surprises there. But the same code using a float behaves very strangely:

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:

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:

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:

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?

By admin | Posted in Uncategorized | Tagged , | Comments (1)

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 *

*
*