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
4

5 Answers

my_var = (int)my_var; 

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

3

Use in C

int C = var_in_float; 

They will convert implicit

1

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?

2

Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...

If one uses gcc (clang?) and have -Werror and -Wbad-function-cast defined,

int val = (int)pow(10,9); 

will result:

error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]

(for a good reason, overflow and where values are rounded needs to be thought out)

EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).

After properly thought out (that parameters to pow() are good), int val = pow(10,9); seems to work with gcc 9.2 x86-64 ...

but note:

printf("%d\n", pow(10,4)); 

may output e.g.

-1121380856 

(did for me) where

int i = pow(10,4); printf("%d\n", i); 

printed

10000 

in one particular case I tried.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy