HotBananaPepper
HotBananaPepper

Reputation: 21

How do I convert the decimal part in a string that holds a double value into a double in C?

I need to convert a string that is a positive valid double (ex: 52.503) into a double without the use of library functions including math.h and string.h. What I'm having most difficulty is in getting the values after the decimal point. If I had pow I would use a for loop and raise 10 to the power of i (i starting at 1 from the 1st value after the decimal point) and use that so I can get the right amount of decimal places. How would I do it without pow?

edit:nvm i solved it

#include <stdio.h>
double convert_to_double(const char *digits);
int main (void) {
char s[10] = "5009.48";
double a = convert_to_double(s);
printf("a is %lf",a);
}

double convert_to_double(const char *digits) { 
    double sum1 = 0;
    double sum2 = 0;
    int i = 0;
    int c = 0;

    while( digits[i] != '.' ) {
        c++;
        i++;
    }

    for (i=0 ; i<c; i++) {  //Records values before decimal into sum1
    sum1 = 10 * sum1 + (digits[i] - '0') ;
    }
    i = c+1;

    while (digits[i] != '\0')  //Records values after decimal point into sum2
    {   
        sum2 = sum2 + (double)(digits[i] - '0')/10; //Input: 5009.48 Output: 0.4+0.8=1.4
        i++;                                              
    }


 return  sum1+sum2;

}

Upvotes: 0

Views: 96

Answers (1)

HotBananaPepper
HotBananaPepper

Reputation: 21

Changed it to this after trying out @weathervane's suggestion

double convert_to_double(const char *digits) { 
    double sum1 = 0;
    int i = 0;
    int c = 0;
    int d = 0;

    while( digits[i] != '.' ) { //Records which index decimal point is located.
        c++;
        i++;
    }

    for (i=0 ; digits[i] != '\0' ; i++) { //Records double value including decimal part as integer.
    if (digits[i] == '.' ) i++;
    sum1 = 10 * sum1 + (digits[i] - '0') ;
    }

    i = c+1;

    while (digits[i] != '\0') { //Records how many values are after decimal point
        d++;
        i++;
    }
    while (d>0) { //Shifts the decimal point by one place to the left d times. 
        sum1 = sum1/10;
        d--;
    }
 return sum1;
}

Upvotes: 1

Related Questions