问题
I'm using C (not C++).
I need to convert a float number into an int
. I do not want to round to the the nearest number, I simply want to eliminate what is after the integer part. Something like
4.9 -> 4.9-> 4
回答1:
my_var = (int)my_var;
As simple as that. Basically you don't need it if the variable is int.
回答2:
Use in C
int C = var_in_float;
They will convert implicit
Thank you
回答3:
If you want to round it to lower, just cast it.
float my_float = 42.8f;
int my_int;
my_int = (int)my_float; // => my_int=42
For other purpose, if you want to round it to nearest, you can make a little function or a define like this:
#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))
float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43
Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.
回答4:
double a = 100.3;
printf("%f %d\n", a, (int)(a* 10.0));
Output Cygwin 100.3 1003
Output MinGW: 100.3 1002
Using (int) to convert double to int seems not to be fail-safe
You can find more about that here: Convert double to int?
来源:https://stackoverflow.com/questions/24723180/c-convert-floating-point-to-int