I wrote a small program to demonstrate a problem im having with a bigger one so you dont have to look thru so much code. I'm having problems when I convert a double to an integer.

``````#include <stdio.h>
#include <stdlib.h>

int main(void)
{
double dNum;
int iNum;
char sNum = "";

printf("Changing a double to int.\n");
printf("Enter a double: ");
fgets(sNum, 15, stdin);
dNum = (atof(sNum))*100;
printf("Double: %f\n", dNum);

iNum = ((int)dNum);
printf("Int: %d\n", iNum);

getch();
return 1;
}``````

The input:
2499.99

The output:
Double: 249999.000000
Int: 249998

Why does it minus one from itself? And how do i make it NOT minus one off itself? Thanks in advance...

Casting to an int is a truncation. The fact that you are not clear on what is gettng truncated is a matter of precision. For instance, if I change your code to print the double to 20 decimal places here is the result I get:

``Changing a …``

Thanks for the speedy reply... but how do i fix this problem?

The 'problem' is that a double can not accurately represent some values. In these cases, you get an approximation of the value you store. I'd suggest not casting from a floating point value to an integer value - …

## All 8 Replies

Casting to an int is a truncation. The fact that you are not clear on what is gettng truncated is a matter of precision. For instance, if I change your code to print the double to 20 decimal places here is the result I get:

``````Changing a double to int.
Enter a double: 2499.99
Double: 249998.99999999997089616954
Int: 249998``````

Which, if you consider the truncation, is perfectly rational.

Thanks for the speedy reply... but how do i fix this problem?

Thanks for the speedy reply... but how do i fix this problem?

The 'problem' is that a double can not accurately represent some values. In these cases, you get an approximation of the value you store. I'd suggest not casting from a floating point value to an integer value - it is full of little problems like this.