How to Check if a Variable is a Float in Python?

While working on a machine learning application, I got a requirement to check if a variable is a float in Python. There are different methods to do this. In this tutorial, I will show you each method with examples of checking a variable type is float in Python.

To check if a variable is a float in Python, you can use the isinstance() function. This built-in function allows you to verify the type of a variable by returning True if the variable is an instance of the specified type. For example, isinstance(x, float) will return True if x is a float.

Check if a Variable is a Float in Python

Now, let me show you how to check if type of variable is float in Python using different methods with examples.

Method 1: Using isinstance()

The isinstance() function in Python is a built-in way to check if a variable is of a specific type. Now, let me show you a few examples.

Example-1:

Here is a basic example to help you understand it better.

x = 3.14

if isinstance(x, float):
    print("x is a float!")
else:
    print("x is not a float.")

In this example, isinstance(x, float) returns True because x is indeed a float.

You can see the output in the screenshot below after I executed the above Python code using VS code.

Check if a Variable is a Float in Python

Example-2:

Let me show you an advanced example.

In the USA, weather data is often recorded in floating-point numbers. Let’s say you have a variable storing the temperature in Fahrenheit, and you want to ensure it’s a float.

temperature = 75.5

if isinstance(temperature, float):
    print("Temperature is recorded correctly as a float.")
else:
    print("Temperature is not recorded as a float.")

This ensures that the temperature data is stored in the correct format for further processing.

Check out How to Check Variable Type is Boolean in Python?

Method 2: Using type()

The type() function returns the type of the object passed to it. You can compare this to float to check if a variable is a float in Python.

Example-1:

Let me show you a basic example.

y = 7.89

if type(y) == float:
    print("y is a float!")
else:
    print("y is not a float.")

Example-2:

Now, let me show you an advanced example.

In the USA, financial transactions often involve decimal values for dollars and cents. Suppose you have a variable representing a transaction amount.

transaction_amount = 19.99

if type(transaction_amount) == float:
    print("Transaction amount is correctly recorded as a float.")
else:
    print("Transaction amount is not recorded as a float.")

This helps in ensuring the accuracy of financial records.

You can see the output in the screenshot below:

python check variable type is float

Read Check Type of Variable Is String in Python

Method 3: Using float() with Exception Handling

You can also attempt to convert a variable to a float and handle any exceptions that arise if the conversion fails. This way, you can check if a variable is a float in Python.

Example-1:

Let me show you a basic example.

z = "12.34"

try:
    float(z)
    print("z can be converted to a float.")
except ValueError:
    print("z cannot be converted to a float.")

Example-2:

Let me show you an advanced example.

When collecting user input for numerical data, such as survey responses or form entries, it’s crucial to validate the input.

user_input = "45.67"

try:
    float(user_input)
    print("User input is a valid float.")
except ValueError:
    print("User input is not a valid float.")

This ensures that user-provided data is in the correct format for processing.

Read How to Check the Type of a Variable in Python?

Method 4: Custom Function

You can also create a custom function to check if a variable is a float in Python.

Example-1:

Here is a simple example to help you understand it.

def is_float(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

a = "56.78"

if is_float(a):
    print("a is a float.")
else:
    print("a is not a float.")

You can see the output in the screenshot below:

check variable type is float in python

Example-2:

Here is another advanced example.

Suppose you’re parsing a CSV file containing mixed data types, and you need to ensure that certain columns contain float values.

import csv

def is_float(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

with open('data.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        value = row[2]  # Assume the third column should be a float
        if is_float(value):
            print(f"{value} is a float.")
        else:
            print(f"{value} is not a float.")

This ensures the integrity of data being processed from external sources.

Conclusion

In this tutorial, I have explained how to check if a variable is a float in Python using different methods like: using isinstance(), type(), exception handling, custom functions, etc.

You may like the following tutorials:

Leave a Comment