# Thread: How to convert from float to int?

1. ## How to convert from float to int?

Hi,
this is a really simple problem, but I just can't find a solution.
How do you convert a float like 12.34 to a rounded integer like 12??

2. If you really want to round the number (i.e. 2.3->2 but 2.6->3) then you need to write your own function. e.g.:
Code:
```#include <math.h>

int Round(float myfloat)
{
double integral;
float fraction = (float)modf(myfloat, &integral);

if (fraction >= 0.5)
integral += 1;
if (fraction <= -0.5)
integral -= 1;

return (int)integral;
}

int main(void)
{
float myfloat;
int myint;
myfloat = 2.3f;
myint = (int)myfloat;
printf("%d\n",myint);
myfloat = 7.6f;
myint = (int)myfloat;
printf("%d\n",myint);
printf("%d\n", Round(2.3f));
printf("%d\n", Round(7.6f));
return 0;
}```
I'm not sure if you strictly need all those casts, but my compiler gives me warnings if I don't include them, and I don't see the harm (maybe someone could tell me if there is a good reason for not explicitly stating casts - thanks!).

3. ## thanks guys, very helpful

thanks thats just what I needed,
many thanks

4. Originally posted by DavT
If you really want to round the number (i.e. 2.3->2 but 2.6->3) then you need to write your own function. e.g.:
Code:
```#include <math.h>

int Round(float myfloat)
{
double integral;
float fraction = (float)modf(myfloat, &integral);

if (fraction >= 0.5)
integral += 1;
if (fraction <= -0.5)
integral -= 1;

return (int)integral;
}```
That would work, but this is much faster (no conditionals to slow you down):

Code:
```int Round(float myfloat)
{
return (int)(myFloat + 0.5);
}```
Works because x rounded to the nearest int is the same as the integer part of x + 0.5.

5. Isn't there a round function in C99?

6. >Isn't there a round function in C99?

Yes.
7.12.9.6 The round functions

Synopsis

1
#include <math.h>
double round(double x);
float roundf(float x);
long double roundl(long double x);

Description

2 The
round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction.

Returns

3 The
round functions return the rounded integer value.

7. Originally posted by DavT
I'm not sure if you strictly need all those casts, but my compiler gives me warnings if I don't include them, and I don't see the harm (maybe someone could tell me if there is a good reason for not explicitly stating casts - thanks!).
The only reason not to cast is because it can suppress more warnings than you meant to suppress. I wish I remembered the details/instances of it happening so I could tell you, but I don't.