Skip to content

Check if a String is a Float in Python AlixaProDev Spark By {Examples}

  • by

How do I check if a string is a number (float) in Python? You can use the float() function with try catch to check if a string is a float or not. In this article, we will explore several different methods for checking if a string is a valid float value with examples.

1. Quick Examples to Check if a String is a Float

These examples will give a high-level idea of each method to check if a string is a float. We will discuss each method in much detail later on.

# Quick examples of checking if a string is a float

# 1. Using float()
def is_float(string):
try:
# float() is a built-in function
float(string)
return True
except ValueError:
return False
print(is_float(“123.456”))

# 2. Using decimal module
import decimal
def is_float_decimal(string):
try:
decimal.Decimal(string)
return True
except decimal.InvalidOperation:
return False

2. Use float() to Check String is a Floating Point Number

The float() function can be used to check if a string is a floating-point number in Python, actually, this method converts a string to a floating-point number however, we can use this to check string contains a float value.

When passed a string that cannot be converted to a float, it raises a ValueError exception. We can use this behavior to check whether a given string represents a valid float value by attempting to convert it using the float() function, and catching the ValueError exception if it is raised.

Let’s create a custom boolean function using the float() function that checks if the string is a valid float or not. See the following example:

# Custom boolean function
def is_float(string):
try:
# Return true if float
float(string)
return True
except ValueError:
# Return False if Error
return False

We can now call this function that will tell us whether our string contains a float value or not.

# We have called the function

# And print the result
print(is_float(‘5.14’))
# True

print(is_float(’42’))
# True

print(is_float(‘6.4179’))
# True

# Underscores are ignored
print(is_float(“1_2_3.4”))
# True

The float() function has some limitations and can give you unexpected results. It ignores the underscore between the digits, consider NaN as a true float, and many others. So make sure to do a test before you use this method.

See the following code which are the exceptions of float() function. You will have an idea of the limitation of the float() function.

# 123.4, underscores ignored
print(is_float(“1_2_3.4”))
# True

# nan is also float
print(is_float(“NaN”))
# True

# Valid Float E is considerd is Exp
print(is_float(“123.E4”))
# True

# Infinity is Float
print(is_float(“-iNF”))
# True

You can not rely on the float() function to check whether a string is a float or not, however, it is a good fit to convert string values to float.

3. Use decimal Module to Check if a String is a Flaot Value

The decimal module in Python provides high-precision decimal arithmetic, it can also be used to check if a given string is a valid decimal number, including floating-point numbers.

The decimal module can handle various edge cases that may arise when checking if a string is a float. It can also be used to round numbers and perform other arithmetic operations.

Example to check if a given string is a valid float:

# We have used the decimal module
from decimal import Decimal, InvalidOperation

def is_decimal(s):
try:
Decimal(s)
return True
except InvalidOperation:
return False

print(is_decimal(“123.456”))
# True
print(is_decimal(“123.4_56”))
# False – underscores not allowed
print(is_decimal(“123.4e5”))
# True
print(is_decimal(“123.4e5.6”))
# False – invalid format
print(is_decimal(“infinity”))
# False – not a decimal
print(is_decimal(“NaN”))
# False – not a decimal
print(is_decimal(“123,456.789”))
# False – commas not allowed
print(is_decimal(“1.797693e+308”))
# True

4. isdigit() and replace() to Find if a String is Float

Another way to check if a string is a valid float is to use the isdigit() and replace() methods. The isdigit() method checks if all the characters in a string are digits, while the replace() method replaces a specified character in a string with another character. We can use these methods in combination to check if a string is a valid float.

num_str = ‘1.43’
# Replace the decimal point with an empty string
num_str_no_decimal = num_str.replace(‘.’, ”, 1)
if num_str_no_decimal.isdigit():
print(num_str)

5. Regular Expression – Check if a String is a Float Number

Regular expressions (regex) can be used to check if a string matches a certain pattern. In the case of checking if a string is a float, a regex pattern can be created to match the format of a float.

# Regular Expression to check against pattern
import re

def isfloat_regex(string):
# We have defined a pattern for float value
pattern = r’^[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?$’
# Find the match and convert to boolean
return bool(re.match(pattern, string))

print(isfloat_regex(“123.456”))
# True
print(isfloat_regex(“123.3E4”))
# True
print(isfloat_regex(“.1”))
# True
print(isfloat_regex(“6.52e-07”))
# True
print(isfloat_regex(“-iNF”))
# False
print(isfloat_regex(“1,234”))
# False

The regular expression from the above examples are made for the following purposes:

[-+]? – An optional sign, either ‘+’ or ‘-‘.

[0-9]* – Zero or more digits.

.? – An optional decimal point.

[0-9]+ – One or more digits.

([eE][-+]?[0-9]+)? – An optional exponent in scientific notation.

$ – End of the string.

6. Summary and Conclusion

We learned various ways to check if a string is a valid float in Python. You have learned that float() function is best fit for this task though it has some limitations. The decimal module provides more precision, however, regular expression gives us more control. I hope this article was helpful, leave questions in the comment section.

Happy Coding!

 How do I check if a string is a number (float) in Python? You can use the float() function with try catch to check if a string is a float or not. In this article, we will explore several different methods for checking if a string is a valid float value with examples. 1. Quick  Read More Python, Python Tutorial, Python String Examples 

Leave a Reply

Your email address will not be published. Required fields are marked *