1
votes

In Objective-C, is it a clean/safe approach to type cast let's say, a floating-point number to an integer with just assigning the floating-point variable to the int variable, and with the format specifier %i in NSLog call?

The proper way to do this is declaring the type cast like this:

int x; 
float y;

y = 7.43;

x = (int) y; //type cast (int)

NSLog(@"The value of x is %i", x);

Output:

The value of x is 7

This type-casting method would be the ideal approach, but I tried to just assign the floating-point variable into the int variable and it works the same, is there a difference?

This is the other method without the (type-cast):

int x;
float y;

y = 7.43;

x = y; // no (int) casting for variable 'y' here

NSLog(@"The value of x is %i", x);

Output:

The value of x is 7

As you can see, is the same result, what's the difference? both methods are good? which is cleaner?

1
The above has nothing to do with format specifiers, as any conversion occurs before you get to the NSLog statement. The thing you don't want to do is NSLog(@"The value of x is %i", y); expecting implicit conversion from float to int to occur -- it won't, and the result will be gibberish (if you don't actually cause a crash). It would be legit to do NSLog(@"The value of x is %i", (int) y);, however.Hot Licks

1 Answers

2
votes

You do not need the explicit cast, but it cannot hurt and it will make your code more readable.

I believe this is safe, mainly because the maximum float is much smaller than a possible int, so there should be no data loss.

Make sure your intention is truncating the decimal part of your float value rather than rounding.