/*********************************************
* @brief 将字符串转换为 double 类型的浮点数
* @param text 要转换的字符串
* @return 转换为 double 类型后的值
********************************************/
double atof(const char* text);
!subtitle:说明
将字符串转换为 double 类型的浮点数。
此函数会丢弃字符串开头的所有空格字符(由 isspace 函数判断),并提取尽可能多的字符来构成有效的浮点数。
支持正负号、十进制数、0x 或 0X 开头的十六进制数、e 或 E 表示的科学计数法、INF 或 INFINITY(忽略大小写)、NAN(忽略大小写)。
!subtitle:参数
text - 要转换的字符串
!subtitle:返回值
返回转换为 double 类型后的值
失败时返回 0.0
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("%f\n", atof(" 3.1415926junk")); // 3.1415926
printf("%f\n", atof(" 2.71828junk")); // 2.71828
printf("%f\n", atof(" 2e10junk")); // 2 乘以 10 的 10 次方
printf("%f\n", atof(" -0xabcdjunk")); // -0xABCD
printf("%f\n", atof(" -inF")); // 负无穷
printf("%f\n", atof(" Nan")); // NAN
printf("%f\n", atof(" junk")); // 失败
return 0;
}
运行结果:
3.141593
2.718280
20000000000.000000
-43981.000000
-inf
nan
0.000000
C23 standard (ISO/IEC 9899:2024):
7.22.1.1 The atof function (p: TBD)
C17 standard (ISO/IEC 9899:2018):
7.22.1.1 The atof function (p: TBD)
C11 standard (ISO/IEC 9899:2011):
7.22.1.1 The atof function (p: 341)
C99 standard (ISO/IEC 9899:1999):
7.20.1.1 The atof function (p: 307)
C89/C90 standard (ISO/IEC 9899:1990):
4.10.1.1 The atof function