将float转换为char*

boo*_*oom 14 c floating-point floating-point-conversion

我如何能转换floatchar*C语言?

Del*_*ani 31

char buffer[64];
int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);

if (ret < 0) {
    return EXIT_FAILURE;
}
if (ret >= sizeof buffer) {
    /* Result was truncated - resize the buffer and retry.
}
Run Code Online (Sandbox Code Playgroud)

那将存储myFloatin 的字符串表示myCharPointer.但要确保字符串足够大以容纳它.

snprintf是一个更好的选择,sprintf因为它保证它永远不会超过你在参数2中提供的缓冲区的大小.

  • 请改用snprintf以确保没有缓冲区溢出. (5认同)

aJ.*_*aJ. 8

char array[10];
sprintf(array, "%f", 3.123);
Run Code Online (Sandbox Code Playgroud)

sprintf :(来自MSDN)


chu*_*ica 7

很久以后接受答案。

使用sprintf(),或相关函数,正如许多其他人建议的答案,但使用更好的格式说明符。

使用"%.*e", 代码解决了各种问题:

  • 所需的最大缓冲区大小要合理得多,例如 18 float(见下文)。使用"%f"sprintf(buf, "%f", FLT_MAX);可能需要 47+。sprintf(buf, "%f", DBL_MAX);可能需要 317+ char

  • 使用".*"允许代码定义区分字符串版本float x和下一个最高版本所需的小数位数float。有关详细信息,请参阅Printf 宽度说明符以保持浮点值的精度

  • Using"%e"允许代码将小floats 彼此区分开来,而不是所有打印"0.000000",这是当|x| < 0.0000005.

示例用法

#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                     //  - d .  dddddddd           e - dddd \0

char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
Run Code Online (Sandbox Code Playgroud)

想法:
IMO,最好将 2x 缓冲区大小用于buf[FLT_STRING_SIZE*2].
为了增加健壮性,请使用snprintf().


作为第二个选择考虑"%.*g"。这就像"%f"期指数接近1.0和值一样"%e"为他人。


bal*_*ena 5

在Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);
Run Code Online (Sandbox Code Playgroud)