C strtod() – String Conversion Function


In this tutorial, you will learn about C programming string conversion library function strtod() with explanation and example. C strtod() is the string conversion function that converts a sequence of characters representing a floating-point value to double.

C strtod() - String Conversion Function

strtod() is defined under the general utilities library <stdlib.h>. Therefore, we should insert stdlib.h before using it in the program.

#include<stdlib.h>

C strtod() function prototype


double strtod( const char *sPtr, char **endPtr );

where,

sPtr = string to be converted

endPtr = pointer to the first character from the converted value in the string

Return Type


strtod() returns 0 if it’s unable to convert any portion of its first argument to double.

This function ignores any whitespace character encountered at the beginning of the string.

C program to illustrate the concept of string conversion function strtod()

//C string conversion function strtod

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

int main()
{
   //initializing string pointer
   const char *sPtr = "40.5% student are pass";

   double n; //variable to store converted string
   char *endPtr; //char type pointer

   n = strtod( sPtr, &endPtr );

   printf("Before Converting: \"%s\"\n", sPtr);
   printf("\nDouble Value: %.3f and string part: \"%s\"\n", n, endPtr);
   return 0;
}

Output
c string conversion function strtod

Explanation

In the above example, variable n is used to store the double value converted from the string sPtr whereas, endPtr is assigned the location of the first character from the converted value in the string.