atof() — Convert Character String to Float
Format
#include <stdlib.h>
double atof(const char *string);
Language Level
ANSI
Threadsafe
Yes
Locale Sensitive
The behavior of this function might be affected by the LC_CTYPE and LC_NUMERIC categories of the current locale. For more information, see Understanding CCSIDs and Locales.
Description
The atof()
function
converts a character string to a double-precision floating-point value.
The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number. This character can be the null character that ends the string.
The atof()
function
expects a string in the following form:
The white space consists of the same characters for which
the isspace()
function
is true, such as spaces and tabs. The atof()
function
ignores leading white-space characters.
For the atof()
function, digits is
one or more decimal digits; if no digits appear before the decimal
point, at least one digit must appear after the decimal point. The
decimal digits can precede an exponent, introduced by the letter e
or E. The exponent is a decimal integer, which might be signed.
The atof()
function
will not fail if a character other than a digit follows an E or
if e is read in as an exponent. For example, 100elf will
be converted to the floating-point value 100.0. The accuracy
is up to 17 significant character digits.
Return Value
The atof()
function
returns a double value that is produced by interpreting the
input characters as a number. The return value is 0 if the
function cannot convert the input to a value of that type. In case
of overflow, the function sets errno to ERANGE and
returns the value -HUGE_VAL or +HUGE_VAL.
Example
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
double x;
char *s;
s = " -2309.12E-15";
x = atof(s); /* x = -2309.12E-15 */
printf("x = %.4e\n",x);
}
/******************* Output should be similar to: ***************
x = -2.3091e-12
*/
Related Information
- atoi() — Convert Character String to Integer
- atol() – atoll() — Convert Character String to Long or Long Long Integer
- strtol() – strtoll() — Convert Character String to Long and Long Long Integer
- strtod() - strtof() - strtold() — Convert Character String to Double, Float, and Long Double
- strtod32() - strtod64() - strtod128() — Convert Character String to Decimal Floating-Point
- <stdlib.h>