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 (2)

2 Comments

  1. Posted March 30, 2011 at 11:30 pm | Permalink

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

  2. Lorien
    Posted March 31, 2011 at 9:33 am | Permalink

    Oh, that is probably it then. I wonder what type it thinks it is?

Post a Comment

Your email is never shared. Required fields are marked *

*
*