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