Convert a String to a Float in C
In C, we can convert a string to a float using functions such as atof(), strtof(), and sscanf().
In this tutorial, we will explore multiple methods to convert a string to a float with clear explanations and examples.
Examples of Converting a String to a Float in C
1. Using atof() to Convert a String to a Float
In this example, we use the atof() function from stdlib.h to convert a string to a float.
main.c
</>
Copy
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "3.14159";
float num;
// Convert string to float using atof
num = atof(str);
printf("Converted float value: %f\n", num);
return 0;
}
Explanation:
- We declare a string
str[] = "3.14159"containing a numerical value in text format. - The function
atof(str)converts the string to a float and stores it innum. - We use
printf()to display the converted float value.
Output:
Converted float value: 3.141590
2. Using strtof() for Safer Conversion from String to Float
Here, we use strtof(), which allows error handling by checking if the entire string was successfully converted.
main.c
</>
Copy
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[] = "45.67xyz";
char *endPtr;
float num;
// Convert string to float using strtof
num = strtof(str, &endPtr);
if (*endPtr == '\0') {
printf("Converted float value: %f\n", num);
} else {
printf("Partial conversion occurred: %f (remaining: %s)\n", num, endPtr);
}
return 0;
}
Explanation:
- We declare a string
str[] = "45.67xyz", which contains extra non-numeric characters. - The function
strtof(str, &endPtr)converts the numeric part of the string to a float. - The
endPtrpointer indicates where the conversion stopped. - If
*endPtris'\0', the entire string was converted; otherwise, extra characters remain.
Output:
Partial conversion occurred: 45.669998 (remaining: xyz)
3. Using sscanf() to Extract a Float
Here, we use sscanf() to extract a float from a string efficiently.
main.c
</>
Copy
#include <stdio.h>
int main() {
char str[] = "123.45";
float num;
// Convert string to float using sscanf
if (sscanf(str, "%f", &num) == 1) {
printf("Converted float value: %f\n", num);
} else {
printf("Conversion failed!\n");
}
return 0;
}
Explanation:
- We declare a string
str[] = "123.45"containing a floating-point number. - The function
sscanf(str, "%f", &num)extracts the float value. - If
sscanf()returns 1, the conversion succeeded. - We use
printf()to display the converted float value.
Output:
Converted float value: 123.449997
Conclusion
In this tutorial, we explored multiple ways to convert a string to a float in C:
- Using
atof(): Simple but lacks error handling. - Using
strtof(): More robust as it provides error detection. - Using
sscanf(): Useful for extracting floats from formatted input.
