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[15] = "";
    
    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...

Recommended Answers

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.

Add 0.05 before the truncation.

i suggest you to add +1 to the integer number before printing it. or u can try using ceil() function in math.h

At least with GNU GCC, there is not need to reinvent the wheel, they are declare (very logically) in math.h: http://www.gnu.org/s/hello/manual/libc/Rounding-Functions.html. As that is standard header they could be even part of standard:
http://en.wikipedia.org/wiki/Math.h

Sure. And when you need to actually know how to do it because your next language doesn't have math.h, what do you do? People should not be relying on library functions for this easy stuff as a new student. They need to understand the underlying concepts first.

Hey WALTP! thnx a heap... it works a charm... appreciate it buddy...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.