How can I convert a float value to char* in C language?
- 6,755
- 4
- 35
- 54
- 5,602
- 23
- 57
- 92
-
9You'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? – crazyscot Jun 07 '10 at 10:46
7 Answers
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.
- 14,478
- 1
- 42
- 66
- 76,631
- 25
- 162
- 208
-
@aJ When the value is printed in buffer will the same print statement be printed on console as well.... – boom Jun 07 '10 at 11:00
-
sprintf will write the float value in buffer. If you want to print the same to console use printf("%f" ... – aJ. Jun 07 '10 at 11:02
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 for
float(see below). With"%f",sprintf(buf, "%f", FLT_MAX);could need 47+.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 offloat xand it next highestfloat. For deatils, see Printf width specifier to maintain precision of floating-point valueUsing
"%e"allows code to distinguish smallfloats from each other rather than all printing"0.000000"which is the result when|x| < 0.0000005.
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.
- 127,356
- 13
- 118
- 231
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.
- 93
- 5
-
-
1
-
Yes. I use uint8_t. BTW the simplest (but not safe) way is just to cast pointers ^^ – Peter Mar 15 '19 at 21:08
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);
- 29,113
- 9
- 48
- 60
-
2+1 even though it must specified it is a GNU extension afaik. (asprintf is a GNU ext I mean) – ShinTakezou Jun 07 '10 at 10:55