w3resource

C strtod() function

C strtod() function - Convert strings to a double-precision value

Syntax strtod() function

double strtod(const char *str, char **endptr)

The strtod() function used to convert the string pointed to by the argument str to a floating-point number (type double). The function stop reading the string at the first character that is not recognized as part of a number.

Parameters strtod() function

Name Description Required /Optional
str Null-terminated string to convert. Required
endptr Pointer to character that stops scan. Required

Return value from strtod()

  • Upon successful completion, the function returns the converted value.
  • If no conversion could be performed, 0 shall be returned.

Example: strtod() function

The following example shows the usage of strtod() function.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   char *string, *stopstring;
   double x;
   float f;
   long double ld;

   string = "1112.34Red Green White";
   x = strtod(string, &stopstring);
   printf("String = %s\n", string);
   printf("Stopped scan at %s\n", stopstring);
   printf("After converting the said string to a double-precision number\nValue = %f\n", x);
   
   string = "100abcdef";
   x = strtod(string, &stopstring);
   printf("\nString = %s\n", string);
   printf("Stopped scan at %s\n", stopstring);
   printf("After converting the said string to a double-precision number\nValue = %f\n", x);

   string = "100  abc";
   x = strtod(string, &stopstring);
   printf("\nString = %s\n", string);
   printf("Stopped scan at %s\n", stopstring);
   printf("After converting the said string to a double-precision number\nValue = %f\n", x);
   
   string = "abc100";
   x = strtod(string, &stopstring);
   printf("\nString = %s\n", string);
   printf("Stopped scan at %s\n", stopstring);
   printf("After converting the said string to a double-precision number\nValue = %f\n", x);
}

Output:

String = 1112.34Red Green White
Stopped scan at Red Green White
After converting the said string to a double-precision number
Value = 1112.340000

String = 100abcdef
Stopped scan at abcdef
After converting the said string to a double-precision number
Value = 100.000000

String = 100  abc
Stopped scan at   abc
After converting the said string to a double-precision number
Value = 100.000000

String = abc100
Stopped scan at abc100
After converting the said string to a double-precision number
Value = 0.000000

C Programming Code Editor:

Previous C Programming: C atol()
Next C Programming: C strtol()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdlib/c-strtod.php