Converting float to char*
Asked Answered
E

9

23

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

Eviscerate answered 7/6, 2010 at 10:44 Comment(1)
You'll need to be more specific. What do you want - a textual representation of the decimal value of the float? A stream of bytes you can pass around easily and use to reconstitute the float later?Potomac
B
43
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.

Bitartrate answered 7/6, 2010 at 10:47 Comment(0)
G
16

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);
Gaitan answered 3/2, 2015 at 17:20 Comment(0)
G
12
char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

Guacin answered 7/6, 2010 at 10:46 Comment(2)
@aJ When the value is printed in buffer will the same print statement be printed on console as well....Eviscerate
sprintf will write the float value in buffer. If you want to print the same to console use printf("%f" ...Guacin
I
10

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 with "%.*e", like 18 for float (see below). With "%f", (think fixed-point), sprintf(buf, "%f", FLT_MAX); could need 47+ char. sprintf(buf, "%f", DBL_MAX); may need 317+ char.

  • 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 details, 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 with "%f".

Example usage:

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

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


As a 2nd alterative consider "%.*g". It is like "%f" for values exponentially near 1.0 and like "%e" for others.

Isreal answered 3/2, 2015 at 19:23 Comment(0)
P
2
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);
Paratyphoid answered 7/6, 2010 at 10:51 Comment(1)
+1 even though it must specified it is a GNU extension afaik. (asprintf is a GNU ext I mean)Transcript
B
2
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.

Bourbonism answered 12/2, 2015 at 6:18 Comment(3)
Upd: do not forget about processor's endianness!Bourbonism
type unsigned char is highly advisable for the array in this union.Mare
Yes. I use uint8_t. BTW the simplest (but not safe) way is just to cast pointers ^^Bourbonism
P
0
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
Pierrepierrepont answered 7/6, 2010 at 13:2 Comment(0)
J
0
// float arr to bytes
int arr_len = 3;
float x[3] = {1.123, 2.123, 3.123};
char* bytes = new char[arr_len * sizeof(float)];
memcpy(bytes, x, arr_len * sizeof(float));

// bytes to float arr
float y[3];
memcpy(y, bytes, arr_len * sizeof(float));
Jaymejaymee answered 27/10, 2022 at 9:39 Comment(1)
Please provide more supporting information to your answer.Lanky
M
-1

Convert float to binary via ascii codes

float u = 2.154328
string s = to_string(u);
char* p = (char*) s;

This stores the characters, 2, .,1, 5, ..., or in binary 00000010,00101110, 00000001, ...

Mary answered 8/2, 2023 at 21:38 Comment(1)
This is not C.Zeist

© 2022 - 2024 — McMap. All rights reserved.