Algorithm


  1. Input: Accept a string as input.

  2. Function Definition (is_float):

    • Define a function is_float that takes a string as a parameter.
  3. Try-Except Block:

    • Use a try block to encapsulate the following code:
      • Attempt to convert the input string to a float using float(string).
      • If successful, set the result to a variable (e.g., float_value).
  4. Return True or False:

    • If the conversion is successful, return True from the function.
    • If a ValueError occurs during conversion, catch the error in the except block.
    • In the except block, return False since the string is not a valid floating-point number.
  5. Example Usage:

    • Get user input (string) to check if it is a valid floating-point number.
    • Call the is_float function with the user input as an argument.
  6. Output:

    • Display a message indicating whether the input string is a valid floating-point number based on the return value of the is_float function.

 

Code Examples

#1 Code Example with Python Programming

Code - Python Programming

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

# Example usage:
user_input = input("Enter a string: ")
if is_float(user_input):
    print(f"{user_input} is a valid floating-point number.")
else:
    print(f"{user_input} is not a valid floating-point number.")
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: 3.14
3.14 is a valid floating-point number.
Advertisements

Demonstration


Python Programing Example to Check If a String Is a Number (Float)-DevsEnv