Discussion Locked

Convert Integer to Float in C

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I want to convert an integer value into a float value in Turbo C. A friend told me that there is possibility of convert Float into int. Any one help me.

5 replies

by awimsatt

I believe the two functions you want are itof() and ftoi() ( read I-to-F or Int to Float ). It's been a while since I've coded C though.

by csmith

From your question I could not glean enough information about the application to figure out which coversion you need.
Is "Type Promotion" applicable?
Type promotion is where you have mixed data. (In your case float and integer) and you want to add them.
//Example 1:

int i;
float f;
float sum;

sum = (f + i) ;

Or do you need a "Cast" construct?
Casts are used to force an expression to be a specific type.
//Example 2:

int x , y ;
float fraction ;

fraction = (float) x / y ;

Regards, Chris

by somu_rec

Type casting is the best way for compatible data types like int,float turbo c normaly does automatic type casting during the execution of statements
ex if you have a computing stament involving int and float data types int a+float b the resulting answer will only be an int and not an float

explicit type casting can also be done
example
float a;
int b;
(float)b will give an float value of the int b and
(int)a will give an int value of the float a

by kc_gopal

Type casting seems to be the best option for you. You can either declare a float variable and assign the int value to it or use the casting operator to convert the int value for the operation.
Method 1

int i;
float f;
i = 10;
f = i;

Method 2
int i;
(float)i

This discussion is closed to new replies.