Search code examples
cstrtod

strtod with limited string length


If I want to parse the first 3 characters from the char array as a double, ignoring the following characters, do I really need to do this?

int main() {
    const char a[] = "1.23";
    char *b = malloc(sizeof(char) * 4);

    memcpy(b, a, sizeof(char) * 3);
    b[3] = '\0';

    printf("%f\n", strtod(b, NULL)); // Prints 1.20000, which is what I want

    free(b);
}

Isn't there a function like strtod that allows you to specify the maximum string length it should be searching for digits?

Edit: I want it to print 1.2 (which it currently does), not 1.23!


Solution

  • If you always want to only consider the three first characters from a given string, you can use the following code:

    #include <stdio.h>
    #include <string.h>
    
    double parse_double(const char *str) {
      char *tmp = 0;
      double result = 0;
    
      asprintf(&tmp, "%.3s", str);
      result = strtod(tmp, 0);
      free(tmp);
    
      return result;
    }
    
    int main(void) {
      printf("%f\n", parse_double("1.23")); // 1.2
      printf("%f\n", parse_double("1234")); // 123
      printf("%f\n", parse_double("0.09")); // 0.0
    
      return 0;
    }