# Thread: Convert double to int

1. ## Convert double to int

I need to know how to convert a number of the type double to a number of the type int. My double numbers have a lot of digits behind the decimal point and I need to have these properly rounded(not a 'ceil' or 'floor' type of rounding) after the conversion has taken place. Is there a simple way to do this? What is the best way to do it? Below is some code that does not work.
Code:
```#include <stdio.h>
#include <math.h>

int main()
{
double x, y;
int a, b;
x = 3.322884;
y = 3.700219;
a = x;
b = y;
printf("a = %d, b = %d\n", a, b);
}```

2. Add whatever your rounding point is to it, then just assign it to an integer.

Quzah.

3. Something like this?
Code:
```#include <stdio.h>
#include <math.h>

int main()
{
double x, y;
int a, b;
x = 3.322884;
y = 3.700219;
x += .5;
y += .5;
a = x;
b = y;
printf("a = %d, b = %d\n", a, b);
}```

4. Ditto...

mw

5. That's why we both said to add the rounding point and then assign to an int.

Quzah.

6. Add .5 and round down. Thanks, it worked.

7. Add 0.5 and truncate, I might say. But do you also need to consider negative values?
Code:
```#include <stdio.h>

int foo(double value)
{
return value < 0 ? value - 0.5 : value + 0.5;
}

int bar(double value)
{
return value + 0.5;
}

int main()
{
double x = 3.322884;
double y = 3.700219;
printf("foo(%f) = %d, foo(%f) = %d\n", x, foo(x), y, foo(y));
printf("bar(%f) = %d, bar(%f) = %d\n", x, bar(x), y, bar(y));
x = -x;
y = -y;
printf("foo(%f) = %d, foo(%f) = %d\n", x, foo(x), y, foo(y));
printf("bar(%f) = %d, bar(%f) = %d\n", x, bar(x), y, bar(y));
return 0;
}

/* my output
foo(3.322884) = 3, foo(3.700219) = 4
bar(3.322884) = 3, bar(3.700219) = 4
foo(-3.322884) = -3, foo(-3.700219) = -4
bar(-3.322884) = -2, bar(-3.700219) = -3
*/```
Then perhaps it might be: increase distance from zero by 0.5.

8. thetinman,

If your compiler supports C99, you can use lround(), it takes a double and returns a long.