Hi,
How can i convert a float value to char* in C language
Hi,
How can i convert a float value to char* in C language
sprintf(myCharPointer, "%f", myFloat);
That will store the string representation of myFloat
in myCharPointer
. Make sure that the string is large enough to hold it, though.
Edit: thanks to JeremyP, snprintf
is a better option as you can specify the char pointer's size as an argument after the pointer is passed so that an overflow is prevented.
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);