46

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
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
A. O.
  • 670
  • 1
  • 6
  • 16
  • 8
    Enough about the haircut - it is just a cast that you require – Ed Heal Jul 13 '14 at 13:30
  • I don't understand what you mean by “convert an `int` to a binary number”—`int` already _is_ binary… Or do you mean to convert it to a string of the binary representation, e.g. convert `14` to `"1110"`. Either way: How did the floating point numbers get into that conversion? – mafso Jul 13 '14 at 13:34
  • After reading User 3195614's answer: Maybe the confusion comes from integer division evaluating to integers? `5 / 2` evaluates to `2` in C, not to `2.5`. – mafso Jul 13 '14 at 13:40
  • anything that has a decimal point is going to be handled as float or larger. The way to get the value is either the lib function int floor(float) or (for roundingup) int ceil(float). – user3629249 Jul 14 '14 at 04:17

5 Answers5

75
my_var = (int)my_var;

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

Zach P
  • 1,731
  • 11
  • 16
  • 3
    Make sure you do what you want/should for negative and large numbers. Things may be more complicated. If the floats are positive and smaller than the maximum integer on your platform, you ara safe. – Jakub Jul 13 '14 at 14:25
  • 4
    This is nice, but it is also undefined behaviour. – saolof Aug 21 '19 at 14:49
17

Use in C

int C = var_in_float;

They will convert implicit

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
user3161739
  • 171
  • 2
13

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.

AdriZ
  • 393
  • 3
  • 9
  • 3
    Using Macros with logic is not incredibly smart, as people tend to view them as functions. For example if you were to `FLOAT_TO_INT(rand())` it would behave weird, better to make it a function – DownloadPizza May 18 '20 at 15:29
  • 3
    regarding: `#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))` Those literals `0.5` is a `double` You really want `float`. Suggest: `#define FLOAT_TO_INT(x) ((x)>=0.0f?(int)((x)+0.5f):(int)((x)-0.5f)) – user3629249 Aug 27 '20 at 03:11
  • 3
    " round it to lower" is incorrect/unclear for negative values. `(int)` truncates the fraction. – chux - Reinstate Monica Aug 27 '20 at 09:05
  • 2
    @user3629249 `(x)+0.5f` can give incorrect rounded results when the sum is inexact. `(x)+0.5` avoids this by using wider `double` math. IAC `lroundf()`, `roundf()` is better. – chux - Reinstate Monica Aug 27 '20 at 09:08
6
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?

Legu
  • 71
  • 1
  • 3
0

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.

tomi
  • 153
  • 1
  • 4
  • 2
    pow returns a double, that's why you can't print it using `%d`. And using pow for that purpose is wrong because it may return incorrect results for integers. Use 1e4 instead to get 10^4. See [Why does gcc compiler output pow(10,2) as 99 not 100?](https://stackoverflow.com/q/25474351/995714), [Why pow(10,5) = 9,999 in C++](https://stackoverflow.com/q/9704195/995714), [Why does pow(5,2) become 24?](https://stackoverflow.com/q/22264236/995714) – phuclv Aug 27 '20 at 03:05
  • OOh, this (int)14e was great. Is it safe? 1e4 w/o casting has type 'double' (as the pow() case) – tomi Aug 29 '20 at 21:09
  • Lost change to edit above comment more -- just recently I had use case for `1e6`, but (as usual) I used `printf("%d\n", 1e6);` to test it out and got weird results. if `const int million = 1e6` is found safe I start using such a format. – tomi Aug 29 '20 at 21:32
  • 1
    `1e6` relies on the compiler to make a quality `double` to `int` conversion. Less likely a problem than `pow()`, yet I see no C spec guaranteeing the best answer. Alternatives to `(int)1e6`: [Why write 1,000,000,000 as 1000*1000*1000 in C?](https://stackoverflow.com/q/40633059/2410359) and [why not safe](https://stackoverflow.com/a/40637622/2410359) – chux - Reinstate Monica Aug 29 '20 at 22:31
  • yes `pow()` is bad, compared to `10e4` in this example (have to fix, with edit commit). I wondered why that `10e4` is `double` not `int`, then tried `1.12e1` and `12e-3` to understand. – tomi Aug 31 '20 at 15:11