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

Objective CCastingFloating Point

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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.

Solution 2 - Objective C

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)

Solution 3 - Objective C

int myInt = (int) myFloat;

Worked fine for me.

int myInt = [[NSNumber numberWithFloat:myFloat] intValue];

Well, that is one option. If you like the detour, I could think of some using NSString. Why easy, when there is a complicated alternative? :)

Solution 4 - Objective C

You can also use C's lroundf(myFloat).


An incredibly useful tip: In Xcode's editor, type your code as say

myInt = roundf(someFloat);

then control/right-click on roundf and Jump to definition (or simply command-click).

You will then clearly see the very long list of the functions available to you. (It's impossible to remember them all, so just use this trick.)

For example, in the example at hand it's likely that lrintf is what you want.

A further tip: to get documentation on those many functions. In your Terminal.app (or any shell - nothing to do with Xcode, just the normal Terminal.app) simply type man lrintf and it will give you full info. Hope it helps someone.

Solution 5 - Objective C

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.

Solution 6 - Objective C

Here's a more terse approach that was introduced in 2012:

myInt = @(myFloat).intValue;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick LockingView Question on Stackoverflow
Solution 1 - Objective CunwindView Answer on Stackoverflow
Solution 2 - Objective CAlnitakView Answer on Stackoverflow
Solution 3 - Objective CHermann KleckerView Answer on Stackoverflow
Solution 4 - Objective CjmcharnesView Answer on Stackoverflow
Solution 5 - Objective CMatthew SchinckelView Answer on Stackoverflow
Solution 6 - Objective CKy.View Answer on Stackoverflow