C language Atof () function: Converts a string to a double (dual-precision floating-point number)

Source: Internet
Author: User

Header files: #include <stdlib.h>

The function atof () is used to convert a string to a double-precision floating-point number (double) whose prototype is:
Double atof (const char* str);

The name of Atof () is derived from the abbreviation of the ASCII to floating point numbers, which scans the parameter str string, skips the preceding whitespace characters (such as spaces, tab indents, etc., which can be detected by the Isspace () function), The conversion is not started until a number or sign is encountered, and the conversion is ended with a non-numeric or string ending (' + '), and the result is returned. The parameter str string can contain a positive sign, a decimal point, or E (e) to represent an exponential portion, such as 123. 456 or 123e-2.

return value returns the converted floating-point number, or 0.0 if the string str cannot be converted to double.

Warm tip: ANSI C specification defines stof (), Atoi (), Atol (), strtod (), Strtol (), Strtoul () a total of 6 functions that can convert a string to a number, you can compare learning; use Atof () and use Strtod ( STR, NULL) results are the same. In addition in the C99/C++11 specification added 5 functions, namely Atoll (), Strtof (), Strtold (), Strtoll (), Strtoull (), do not introduce, please learn by yourselves.

Example:
#include <stdio.h> #include <stdlib.h>int main () {    char *a = " -100.23",         *b = "200e-2",         *c = "341",         *d = "100.34cyuyan",         *e = "Cyuyan";    printf ("A =%.2f\n", Atof (a));    printf ("B =%.2f\n", atof (b));    printf ("c =%.2f\n", Atof (c));    printf ("D =%.2f\n", atof (d));    printf ("E =%.2f\n", Atof (e));    System ("pause");    return 0;}
Execution Result:
A =-100.23
b = 2.00
c = 341.00
D = 100.34
E = 0.00

C language Atof () function: Converts a string to a double (dual-precision floating-point number)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.