John Smith John Smith - 22 days ago 10
C Question

String converts to an integer instead of double

I want my function to convert a string to a double but if I type for example '22.4' it will output '22'. How do I get it to output a double?(USING fgets) I've read other questions that had answers saying use sscanf but is there a way for using fgets?

double getDouble(char message[]){

double val;
double var = 0.0;
char input[80];

do{
printf("%s\n", message);
fgets(input, 80, stdin);

if (input[strlen(input)-1] == '\n'){
input[strlen(input)-1] = '\0';
}
val = atof(input);

if (val != 0.0){
var = 1.0;
}
else{
printf("Error. Please try again.(Only entering numbers is valid)\n");
}
}while(var == 0.0);
printf("The result is: %f\n", val);

return val;


}

Answer

Here is a working example.

Some modifications:

  • Using a near_equal() function, as testing equality of doubles is dangerous.
  • Instead of using a double flag such as var = 0.0, why not just use an int?
  • Checking the return value of fgets is always a good idea.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <math.h>
    
    #define BUFFSIZE 80
    #define EPSILON 1e-8
    
    double getDouble(char message[]);
    int double_equal(double a, double b);
    
    int
    main(void) {
        double num;
    
        num = getDouble("Enter a real number: ");
    
        printf("The number you entered was %g\n", num);
    
        return 0;
    }
    
    double
    getDouble(char message[]) {
        double val;
        char input[BUFFSIZE];
        int found = 0;
    
        do {
            printf("%s\n", message);
            if (fgets(input, BUFFSIZE, stdin) != NULL) {
                if (input[strlen(input)-1] == '\n'){
                    input[strlen(input)-1] = '\0';
                }
                val = atof(input);
    
                if (!double_equal(val, 0.0)) {
                    found = 1;
                } else {
                    printf("Error. Please try again.(Only entering numbers is valid)\n");  
                }
            } 
        } while (found == 0);
    
        printf("The result is: %.1f\n", val);
    
        return val;
    } 
    
    int
    double_equal(double a, double b) {
        return fabs(a-b) < EPSILON;
    }