C Data Type Functions - C strtof

Convert string to float


float strtof (const char* str, char** endptr);


This function has the following parameter.

C-string beginning with the representation of a floating-point number.
Reference to an already allocated object of type char*, whose value is set by the function to the next character in str after the numerical value.


returns the converted floating point number as a value of type float.

If no valid conversion could be performed, the function returns zero ( 0.0F).

If the correct value is out of the range of representable values for the type, a positive or negative HUGE_VALF is returned, and errno is set to ERANGE.


#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtof */
/*from  ww w .j a v  a  2  s .  c o  m*/
int main (){
  char szOrbits[] = "123.97 123.24";
  char* pEnd;
  float f1, f2;
  f1 = strtof (szOrbits, &pEnd);
  f2 = strtof (pEnd, NULL);
  printf ("%.2f \n", f1/f2);
  return 0;


The code above generates the following result.

Example 2

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
 //from ww  w. j  a  va 2 s  .  c om
int main(void)
    const char *p = "123.11 -2.22 0X1.BC23A3D23A3D7P+6  1.23233e+2323zzz";
    printf("Parsing '%s':\n", p);
    char *end;
    for (double f = strtod(p, &end); p != end; f = strtod(p, &end)){
        printf("'%.*s' -> ", (int)(end-p), p);
        p = end;
        if (errno == ERANGE){
            printf("range error, got ");
            errno = 0;
        printf("%f\n", f);

The code above generates the following result.