tags:

views:

172

answers:

4

Hi,

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

+2  A: 
char array[10];
sprintf(array, "%f", 3.123);

sprintf: (from MSDN)

aJ
@aJ When the value is printed in buffer will the same print statement be printed on console as well....
iSight
sprintf will write the float value in buffer. If you want to print the same to console use printf("%f" ...
aJ
+8  A: 
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.

Delan Azabani
Use snprintf instead to ensure no buffer overrun.
JeremyP
Great idea! I'll add that to my answer...
Delan Azabani
+1  A: 
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);
pixelbeat
+1 even though it must specified it is a GNU extension afaik. (asprintf is a GNU ext I mean)
ShinTakezou
+1  A: 
char array[10];
snprintf(array, sizeof(array), "%f", 3.333333);
pcent