Hi!
can somebody please tell me how to avoid floating point overflow error? Mine is a very big program that uses double data type.
Is there any way in which I can roundoff double numbers to upto certain digit?

get keyboard input as a string then do whatever you want with the individual digits.

He didn't specify that the floating point number was inputed off the command line, but the string idea will work nonetheless as long as you enumerate through the string until you reach the "." character after which you can convert the character(s) number(s) into an integer and proceed to the logical operations that determine if a one should be added or not.

However, if you're true reason for rounding is so that you have a percise number to output than you should wait until you're about to output it and can use, but no limited, to one of the following:

// If you want to display 2 digits passed the decimal point
C - printf("%.2f", floatingNumber);

// same as above but using the C++ standard library
C++ - cout << "Set percision: " << setpercision(number) << DoubleNumber;

// More info: http://msdn2.microsoft.com/en-us/library/wyk4d9cy.aspx
Math.round(double number); // Round to the nearest integer

I've go to go to work, I'll post a function that will round a double number when I return.

Good luck, LamaBot

Back from work...

Here is a simple program that'll illustrate how to use strings to convert floating point values (represented as a string) to an integer:

#include <stdlib.h>
#include <stdio.h>
 
int DoubleRound(char *fnum);
int main() {
    char dnum[] = "92.45972340958723";
    printf("%d",Double2Integer(dnum));
 return 0;
}
int Double2Integer(char *fnum) {
    int integeri = atoi(fnum),i,j,k;
    char hex = 0x30;
    i=k=0;
 
    while (fnum[i] != '.') i++;
    j = strlen(fnum);
    for (;j>i;j--) {
        switch(fnum[j]) {
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                while (fnum[j-1] != hex)
                    hex++;
                hex++;
                fnum[j-1] = hex;
                break;
        }
    }
    switch(fnum[i+1]) {
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            integeri++;
            break;
    }
    return integeri;
}

Please not that the code is an illustration but might not be considered good programming in some views. I hope I helped.

Good luck, LamaBot

This article has been dead for over six months. Start a new discussion instead.