OneBite.Dev - Coding blog in a bite size

convert variable from string to float in C

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

  float fnum; 
  char snum[20];
  strcpy(snum,"12.345"); 
  fnum = atof(snum);

We start off by declaring a float variable called “fnum” and a character array called “snum” with a size of 20. The character array is used to store the string value of “12.345”. Then we use the string copy function to copy the string “12.345” into the character array snum. Lastly, we use the atof() function to convert the string value of “12.345” into a float value and store it in the variable fnum. The atof() function takes a character array as an argument and converts the string to a float value and returns it.

c