Python - How to Check if String is Float Value


Python - Check if string is float value

To check if a string is a float in Python, you can use a try-except block, where in the try block we use float() function to convert the given string to a floating point value. If the conversion is a success, then the given string is a floating point value. If the float() function raises a ValueError exception, then the given string is not a floating point value.

Let us write the function that takes a string value, and checks if this string is a float value or not, and returns a boolean value of True, if the string is float, or False otherwise.

def is_float(string):
    try:
        float_value = float(string)
        return True
    except ValueError:
        return False

Now, we can call to this function in our programs, whenever we need to check if given string is a float value.

Example

In this example, we shall use the above mentioned function is_float(), to check if given string is a float value or not.

Python Program

def is_float(string):
    try:
        float_value = float(string)
        return True
    except ValueError:
        return False

# Example usage:
string1 = "3.14"
string2 = "Hello"

print(f'Is "{string1}" a float? {is_float(string1)}')
print(f'Is "{string2}" a float? {is_float(string2)}')

Output

Is "3.14" a float? True
Is "Hello" a float? False