C convert section of char array to double

Kyle Weller picture Kyle Weller · Mar 23, 2013 · Viewed 14.3k times · Source

I want to convert a section of a char array to a double. For example I have:

char in_string[] = "4014.84954";

Say I want to convert the first 40 to a double with value 40.0. My code so far:

#include <stdio.h>
#include <stdlib.h> 

int main(int arg) {
  char in_string[] = "4014.84954";
  int i = 0;
  for(i = 0; i <= sizeof(in_string); i++) {
    printf("%c\n", in_string[i]);
    printf("%f\n", atof(&in_string[i]));
  }
}

In each loop atof it converts the char array from the starting pointer I supply all the way to the end of the array. The output is:

4
4014.849540
0
14.849540
1
14.849540
4
4.849540
.
0.849540
8
84954.000000   etc...

How can I convert just a portion of a char array to a double? This must by modular because my real input_string is much more complicated, but I will ensure that the char is a number 0-9.

Answer

Shoe picture Shoe · Mar 23, 2013

The following should work assuming:

I will ensure that the char is a number 0-9.

double toDouble(const char* s, int start, int stop) {
    unsigned long long int m = 1;
    double ret = 0;
    for (int i = stop; i >= start; i--) {
        ret += (s[i] - '0') * m;
        m *= 10;
    }
    return ret;
}

For example for the string 23487 the function will do this calculations:

ret = 0
ret += 7 * 1
ret += 8 * 10
ret += 4 * 100
ret += 3 * 1000
ret += 2 * 10000
ret = 23487