Converting float to char*

2020-05-25 06:49发布

How can I convert a float value to char* in C language?

7条回答
冷血范
2楼-- · 2020-05-25 07:05
typedef union{
    float a;
    char b[4];
} my_union_t;

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

查看更多
beautiful°
3楼-- · 2020-05-25 07:08

Long after accept answer.

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

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

  • 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 x and 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 \0
    
    char buf[FLT_STRING_SIZE];
    sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);
    

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

查看更多
beautiful°
4楼-- · 2020-05-25 07:11
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
查看更多
来,给爷笑一个
5楼-- · 2020-05-25 07:13
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 myFloat in myCharPointer. Make sure that the string is large enough to hold it, though.

snprintf is a better option than sprintf as it guarantees it will never write past the size of the buffer you supply in argument 2.

查看更多
Root(大扎)
6楼-- · 2020-05-25 07:15
char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

查看更多
够拽才男人
7楼-- · 2020-05-25 07:23

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);
查看更多
登录 后发表回答