I always thought when floats get truncated to ints, it always becomes the highest number smaller than the float. However, when the float is between -0.5 and 0, it gets converted to 0 instead of -1! Why is this? Is this language-specific? I am seeing this in objC.
Asked
Active
Viewed 2,986 times
0
-
2Casting a float to an int in C (and hence in objC) *truncates*, meaning that any value in (-1, 1) produces a result of zero. That's not what you're reporting, so something else is going on; if you post some code giving an example, it will be much easier to help you. – Stephen Canon Mar 04 '13 at 12:14
1 Answers
2
Well, the short answer is that your understanding is actually correct:
0 is a greater number than -1.
The longer or more detailed answer depends on how the float number is being converted into an integer. If you want "-1" instead of "0" for a float of "0.5, you may need to write your own implementation that strips the negative off the float, rounds it up or down to an integer, and then add (or multiply a -1, to be precise) the negative sign back onto it.
Here's a bit of code I wrote to demo the differences in implementation:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
float floatNumber = -1.0f;
for(NSInteger index = 0; index < 20; index++)
{
NSLog( @"floatNumber is %4.2f and integer is %d %d", floatNumber, (int) floatNumber, (int)roundf(floatNumber));
floatNumber+=0.1f;
}
}
return 0;
}
Under Xcode, the results come out as:
floatNumber is -1.00 and integer is -1 -1
floatNumber is -0.90 and integer is 0 -1
floatNumber is -0.80 and integer is 0 -1
floatNumber is -0.70 and integer is 0 -1
floatNumber is -0.60 and integer is 0 -1
floatNumber is -0.50 and integer is 0 0
floatNumber is -0.40 and integer is 0 0
floatNumber is -0.30 and integer is 0 0
floatNumber is -0.20 and integer is 0 0
floatNumber is -0.10 and integer is 0 0
floatNumber is 0.00 and integer is 0 0
floatNumber is 0.10 and integer is 0 0
floatNumber is 0.20 and integer is 0 0
floatNumber is 0.30 and integer is 0 0
floatNumber is 0.40 and integer is 0 0
floatNumber is 0.50 and integer is 0 1
floatNumber is 0.60 and integer is 0 1
floatNumber is 0.70 and integer is 0 1
floatNumber is 0.80 and integer is 0 1
floatNumber is 0.90 and integer is 0 1

Michael Dautermann
- 88,797
- 17
- 166
- 215