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?
This question is related to
objective-c
casting
floating-point
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.
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.
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.
Here's a more terse approach that was introduced in 2012:
myInt = @(myFloat).intValue;
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? :)
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)
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? :)
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.
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)
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.
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.
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)
Source: Stackoverflow.com