Check if a String is a Valid Floating-Point Number in C

To check if a string is a valid floating-point number in C, you can use several approaches such as using sscanf or the strtof function. These methods help verify that the string strictly represents a floating-point value without any extra characters.


Example 1: Using sscanf to Validate a Floating-Point String

In this example, we will use sscanf to parse the string and check if it represents a valid floating-point number by ensuring no extra characters are present.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "123.45";
    float num;
    char extra;
    
    // Attempt to parse the string as a float and detect any extra characters
    if (sscanf(str, " %f %c", &num, &extra) == 1) {
        printf("The string is a valid floating-point number: %f\n", num);
    } else {
        printf("The string is NOT a valid floating-point number.\n");
    }
    
    return 0;
}

Explanation:

  1. The variable str holds the string to be validated.
  2. num is used to store the converted floating-point value.
  3. The variable extra detects any additional characters after the number.
  4. sscanf attempts to read a float followed by another character. If only a float is read (return value equals 1), the string is valid.
  5. If extra characters exist, the function returns a value greater than 1, indicating an invalid string format.

Output:

The string is a valid floating-point number: 123.449997

Example 2: Using strtof to Validate a Floating-Point String

In this example, we will use the strtof function to convert the string to a float and then verify that the entire string was consumed during the conversion, which confirms its validity.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[] = "123.45";
    char *endptr;
    float num;
    
    // Convert the string to float using strtof and capture the end pointer
    num = strtof(str, &endptr);
    
    // Check if the conversion consumed the entire string
    if (endptr != str && *endptr == '\0') {
        printf("The string is a valid floating-point number: %f\n", num);
    } else {
        printf("The string is NOT a valid floating-point number.\n");
    }
    
    return 0;
}

Explanation:

  1. The variable str contains the string to be validated.
  2. strtof converts the string to a float, storing the result in num, and sets endptr to the first character after the number.
  3. If endptr equals str, no valid conversion occurred, indicating an invalid string.
  4. If *endptr is not the null character ('\0'), extra characters remain, marking the string as invalid.
  5. When the entire string is consumed, it confirms that the string is a valid floating-point number.

Output:

The string is a valid floating-point number: 123.449997

Conclusion

In this tutorial, we demonstrated two methods to check if a string is a valid floating-point number in C.