C语言 将浮点数转换为字符*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2988791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:37:12  来源:igfitidea点击:

Converting float to char*

cfloating-pointfloating-point-conversion

提问by boom

How can I convert a floatvalue to char*in Clanguage?

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

回答by Delan Azabani

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

That will store the string representation of myFloatin myCharPointer. Make sure that the string is large enough to hold it, though.

这将存储myFloatin的字符串表示形式myCharPointer。但是,请确保绳子足够大以容纳它。

snprintfis a better option than sprintfas it guarantees it will never write past the size of the buffer you supply in argument 2.

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

回答by aJ.

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

sprintf: (from MSDN)

sprintf:(来自 MSDN)

回答by baligena

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

回答by chux - Reinstate Monica

Long after accept answer.

很久以后接受答案。

Use sprintf(), or related functions, as many others have answers suggested, but use a better format specifier.

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

Using "%.*e", code solves various issues:

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

  • The maximum buffer size needed is far more reasonable, like 18. sprintf(buf, "%f", FLT_MAX);could need 47+. sprintf(buf, "%f", DBL_MAX);may need 317+

  • Using ".*"allows code to define the number of decimal places needed to distinguish a string version of float xand it next highest float. For deatils, see Printf width specifier to maintain precision of floating-point value

  • Using "%e"allows code to distinguish small floats from each other rather than all printing "0.000000"which is the result when |x| < 0.0000005.

    #define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                         //  - d .  dddddddd           e - dddd 
    #define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                         //  - d .  dddddddd           e - dddd 
    typedef union{
        float a;
        char b[4];
    } my_union_t;
    
    char buf[FLT_STRING_SIZE]; sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
    char buf[FLT_STRING_SIZE]; sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
  • 所需的最大缓冲区大小要合理得多,例如 18。sprintf(buf, "%f", FLT_MAX);可能需要 47+。sprintf(buf, "%f", DBL_MAX);可能需要 317+

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

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

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

Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2].
For added robustness, use snprintf().

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

回答by Peter

char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);

You can access to float data value byte by byte and send it through 8-bit output buffer (e.g. USART) without casting.

您可以逐字节访问浮点数据值,并通过 8 位输出缓冲区(例如 USART)将其发送,而无需进行强制转换。

回答by pixelbeat

##代码##

回答by pcent

##代码##