How to Check if a String Represents a Number with Decimal in Python?

In this tutorial, I will help you learn how to check if a string represents a number with a decimal in Python. As a data scientist working with US census data, I recently faced an issue where I needed to validate if a string input was a valid decimal number. After researching various methods, I discovered three effective ways to achieve this task, I will explain them with examples.

Check if a String Represents a Number with Decimal in Python

Let’s say you have a string input from a user, and you want to check if it represents a decimal number. For example, you might have a string like "3.14" which is a valid decimal number, but a string like "hello" is not.

Read How to Calculate the Number of Days Between Two Dates in Python

Method 1. Use the isdecimal() Method

Python provides a built-in string method isdecimal() that returns True if all the characters in the string are decimals (0-9). However, this method does not consider the decimal point (.) as a valid character. For example:

print("42".isdecimal()) 
print("3.14".isdecimal()) 
print("John".isdecimal())  

Output:

True
False
False

I have executed the above example code and added the screenshot below.

String Represents a Number with Decimal in Python

As you can see, isdecimal() works well for integers but fails to validate decimal numbers.

Check out How to Get a Week Number from Date in Python

Method 2. Cast the String to Float

A simple and effective way to check if a string represents a number with decimal is to try casting it to a float using the float() function. If the cast succeeds, the string is a valid decimal number. If it raises a ValueError , the string is not a valid number. Here’s an example:

def is_decimal(string):
    try:
        float(string)
        return True
    except ValueError:
        return False

print(is_decimal("3.14"))  
print(is_decimal("42"))   
print(is_decimal("John")) 

Output:

True
True 
False

I have executed the above example code and added the screenshot below.

Check if a String Represents a Number with Decimal in Python

In this example, we define a function is_decimal() that takes a string as input. It tries to convert the string to a float using float(). If the conversion succeeds, it returns True , indicating that the string is a valid decimal number. If a ValueError is raised during the conversion, it catches the exception and returns False.

Check out How to Subtract Number of Days from a Date in Python

Method 3. Use Regular Expressions

Another way to check if a string represents a number with a decimal is by using regular expressions. The re module in Python allows you to define a pattern that matches decimal numbers. Here’s an example:

import re

def is_decimal(string):
    pattern = re.compile(r'^-?\d+(\.\d+)?$')
    return bool(pattern.match(string))

print(is_decimal("3.14")) 
print(is_decimal("-42.0"))  
print(is_decimal("John")) 
print(is_decimal("3.14abc"))

Output:

True
True
False
False

I have executed the above example code and added the screenshot below.

How to Check if a String Represents a Number with Decimal in Python

In this example, we define a regular expression pattern ^-?\d+(\.\d+)?$ that matches strings that start with an optional minus sign (-), followed by one or more digits (\d+), optionally followed by a decimal point and one or more digits ((\.\d+)?). The ^ and $ ensure that the entire string matches the pattern.

Check out How to Get the Day of the Week from a Date in Python

Handle Common Edge Cases

When validating decimal numbers, it’s important to consider some common edge cases:

  1. Leading and trailing whitespace: Use the strip() method to remove any leading or trailing whitespace before checking the string.
print(is_decimal("  3.14  "))  # Output: True
  1. Positive and negative numbers: The examples above handle both positive and negative numbers. Make sure your validation method accounts for the optional minus sign.
  2. Scientific notation: If you need to support scientific notation (e.g., “1.23e-4”), you can modify the regular expression pattern or use a library like numpy that supports parsing scientific notation.
import numpy as np

def is_decimal(string):
    try:
        float(string)
        return True
    except ValueError:
        try:
            np.float64(string)
            return True
        except ValueError:
            return False

print(is_decimal("1.23e-4"))  # Output: True

Check out How to Extract Day Number of the Year from a Date in Python

Conclusion

In this tutorial, we explored different methods to check if a string represents a number with decimals in Python. We learned about the limitations of the isdecimal() method and how to use float() casting and regular expressions to validate decimal numbers. We also discussed common edge cases to consider when validating decimal numbers.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.