6.19.32 strtof Function

Convert string to a single precision floating-point value.

Include

<stdlib.h>

Prototype

float strtof(const char * restrict nptr, char ** restrict endptr);

Argument

nptr
the string to attempt to convert
endptr
pointer to the remainder of the string that was not converted

Return Value

The converted value, or 0 if the conversion could not be performed.

Remarks

The strtof function attempts to convert the first part of the string pointed to by nptr to a float floating-point value.

The initial section consists of any white-space characters.

The subject section represents the floating-point constant to convert and consists of an optional plus or minus sign then one of the following.
  • Decimal digits optionally containing a decimal-point character, then an optional exponent part, being e or E followed by an option sign and decimal digits
  • A 0x or 0X, then a nonempty sequence of hexadecimal digits optionally containing a decimal-point character, then an optional binary exponent part, being p or P, and an optional sign, and decimal digits.
  • one of INF or INFINITY, ignoring case
  • NAN, ignoring case, optionally followed by any sequence contain digits or non-digits:
Conversion stops once an unrecognized character is encountered, thus the subject sequence is defined as the longest subsequence of the input string after the initial section and that is of the expected form. A pointer to the position of the first unrecognizable character in the string is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

The final section consists of characters in the string that were unrecognized in the subject section and which will include the terminating null character of the string. This section of the string will be accessible via the address stored to endptr, provided endptr is not a null pointer.

If the correct value of the conversion is outside the range of representable values, the value of ERANGE is stored in errno and the function returns the type-specific HUGE_VAL value with the same sign as the conversion. If the result underflows, the functions return a value whose magnitude is no greater than the smallest normalized positive number in the return type, but errno is not set.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
{ 
  char * string = " +0.137e2 mSec";
  char * final;
  float result;
  
  result = strtof(string, &final);
  printf("The floating-point conversion of the string \"%s\" is %g; final string part is \"%s\"\n", string, result, final);
}

Example Output

The floating-point conversion of the string " +0.137e2 mSec" is 13.7; final string part is " mSec"