Reputation: 5348
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.
Upvotes: 0
Views: 3312
Reputation: 89509
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
Upvotes: 2