We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I'm using float variables, but I want to convert these variables to integer like: 0.9 .... 1 30.9 .... 31 54.2 .... 54 please give a suggestion thanks very much
I would have guessed that execution would be faster to cast to an int then add 1 as opposed to doing a floating point addition (1 in Nocky's example and .5 in Drew's) then casting to an int. Then again I could be wrong, you could always try it both ways and find out. Walt
Surely casting to int then adding one will always round up? Stefan
I was thinking of something like this but I see there is still one floating point math operation. Unless someone can think of a way to eliminate it, Drew's way might be best.
int Convertor(float fSrc) { if ((fSrc - (int)fsrc) >= 0.5) return ((int)fSrc+1)); // instead of return((int)(fSrc+1)); else return( (int)fSrc); }
You've actually got two floating point operations - the subtraction and the comparison. I think Drew's method is definitely the cheapest and simplest. Stefan
"I think Drew's method is definitely the cheapest and simplest." Yes, for positive numbers only. For negative numbers, you'd want to subtract 0.5 (add -0.5).