How do I convert a float to an int in Objective C?

Viewed 112215

Total newbie question but this is driving me mad! I'm trying this:

myInt = [myFloat integerValue]; 

but I get an error saying essentially integerValue doesn't work on floats.

How do I do it?

6 Answers

I'm pretty sure C-style casting syntax works in Objective C, so try that, too:

int myInt = (int) myFloat;

It might silence a compiler warning, at least.

what's wrong with:

int myInt = myFloat;

bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)

In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.

Anything you can do in regular old ANSI C can be done in Objective-C.

Related