OneBite.Dev - Coding blog in a bite size

convert variable from float to string in C

Code snippet on how to convert variable from float to string in C

  float f = 5.32;
  char s[100];
  sprintf(s, "%f", f);

This code converts a float variable to a string. The first line declares a float variable called “f” and assigns it a value of 5.32. The second line declares a character array (string) called “s” and assigns it a size of 100 elements. The third line uses the sprintf() function to write the characters corresponding to the float value into the string. It takes two parameters, the first being the string to put the float into and the second is the float value to be converted. Lastly, the float value “f” is converted to a string, stored in the character array “s”.

c