Convert a Floating-point value to an Integer in C


Convert float value to an int or Round float value

we can convert very easily,

For Converting floating point value, add 0.5 and convert to integer we can get correct answer,

Explanation:

here,

you can convert floating point to integer but straight conversion has some problem.we cannot get correct value.

if x value 1.9 means.

flaot x=1.9

int a = 1.9

now a has value of 1.it is not correct answer.then,only we add 0.5 then convert integer.

Example

float x=1.9,y=2.4;
int a,b;

a = (int)(x+0.5);
b = (int)(y+0.5);

now you get correct answers,

a has 2.

also,b has 2.

Example Program for Convert float value to an int:

void main()
{
	// Declaring Variables
	float x=1.9,y=2.4;
	int a,b;

	printf("Value Of x:%f",x);
	printf("Value Of y:%f",y);

	// Simple Conversion

	a = (int)(x+0.5);
	b = (int)(y+0.5);
	printf("Value Of a:%d",a);
	printf("Value Of b:%d",b);
}