floating point to int problem?

I have a floating point number that has been input by a user.

I need to multiply it by 10 and use it as an index into a lookup table.

float fnum;
int    inum;

fnum = 65.7;

fnum *=10;  //shows float 657 in the debugger

inum = (int)fnum;  // inum = 656??

Any way to make this work reliably?

Have you tried this:

fnum *=10; //shows float 657 in the debugger
inum = (int)(fnum + 0.5); // rounds off

Note that not all integer values can be exactly expressed in double.
So even when your debugger shows 657, this was maybe internally 656.99996.

You can use library function round() to make it work:

http://www.gnu.org/s/libc/manual/html_node/Rounding-Functions.html

This is also a reason why you should never compare doubles for beeing equal:

if ( ((double)a) == ((double)b) )

as two doubles will not match most of the time. To compare if they are “nearly equal” you should alway do:

if ( abs( a - b) < EPSILON )

where you define EPSILON = 10 e-6 or whatever is exact enough for your application.