我该如何转换 float 价值为 char*C 语?

有帮助吗?

解决方案

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.
}

这将存储字符串表示形式 myFloatmyCharPointer. 。不过,请确保字符串足够大以容纳它。

snprintf 是一个更好的选择 sprintf 因此,它永远不会在参数2中写出您提供的缓冲区的大小。

其他提示

char array[10];
sprintf(array, "%f", 3.123);

Sprintf: :(来自MSDN)

在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);

很久以后接受答案。

利用 sprintf(), ,或相关的功能,正如许多其他功能所建议的,但使用更好的格式指定符。

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

  • 所需的最大缓冲尺寸更为合理,例如18。 sprintf(buf, "%f", FLT_MAX); 可能需要47+。 sprintf(buf, "%f", DBL_MAX); 可能需要317+

  • 使用 ".*" 允许代码定义区分字符串版本所需的小数位数 float x 而且最高 float. 。对于Deatils,请参阅 printf宽度指定符,以保持浮点值的精度

  • 使用 "%e" 允许代码区分小 float彼此而不是全部打印 "0.000000" 这是结果 |x| < 0.0000005.

    #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);
    

想法:
IMO,最好将2倍缓冲尺寸用于刮擦垫 buf[FLT_STRING_SIZE*2].
为了增加鲁棒性,请使用 snprintf().

char* str=NULL;
int len = asprintf(&str, "%g", float_var);
if (len == -1)
  fprintf(stderr, "Error converting float: %m\n");
else
  printf("float is %s\n", str);
free(str);
typedef union{
    float a;
    char b[4];
} my_union_t;

您可以通过字节访问float数据值字节,并通过8位输出缓冲区(例如USART)发送它,而无需铸造。

char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top