Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 688
Nick Locking Avatar asked Nov 13 '08 10:11

Nick Locking


People also ask

Can we change float to int in C?

The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float).

Can you change a float to an int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

What does @() mean in Objective C?

It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.

How do you typecast in Objective C?

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.


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

like image 128
unwind Avatar answered Oct 07 '22 08:10

unwind