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
The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float).
So you cannot store a float value in an int object through simple assignment. You can store the bit pattern for a floating-point value in an int object if the int is at least as wide as the float , either by using memcpy or some kind of casting gymnastics (as other answers have shown).
Convert a float to an int always results in a data loss. The trunc() function returns the integer part of a number. The floor() function returns the largest integer less than or equal to a number. The ceil() function returns the smallest integer greater than or equal to a number.
gcvt() | Convert float value to string in C This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With