Section 4.2 - atof - convert string to double#

Program#

#include <stdio.h>
#include <ctype.h>

/* atof: convert string s to double */

double atof(char s[]);

int main(int argc, char *argv[]) {
    char s[8]="1234.45";
    double d;
    d = atof(s);
    printf("%f", d);
}

double atof(char s[])
{
    double val, power;
    int i, sign;
for (i = 0; isspace(s[i]); i++) /* skip white space */
    ;
    sign = (s[i] == '-') ? -1 : 1;
    if (s[i] == '+' || s[i] == '-')
        i++;
    for (val = 0.0; isdigit(s[i]); i++)
        val = 10.0 * val + (s[i] - '0');
    if (s[i] == '.')
        i++;
    for (power = 1.0; isdigit(s[i]); i++) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10;
    }
    return sign * val / power;
}

Explanation#

In this program, we do the float conversion, by capturing the entire input as decimal first, following the same procedure as converting atoi, that is we keep track of sign, get each character and multiply it’s positional value by 10 and store the output in a variable called val.

Additionally, since it is float, after the decimal, for each decimal we store the power value too as multiples of 10. For e.g 10.21 will be gotten as value = 1021 and power = 100, So that when we return, we can send as 1021/100. We multiply the final by the stored sign and return the result.