C convert floating point to int C convert floating point to int c c

C convert floating point to int


my_var = (int)my_var;

As simple as that. Basically you don't need it if the variable is int.


Use in C

int C = var_in_float;

They will convert implicit


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.