Python regex - Check whether the input is Floating point number or not


Floating point numbers play a crucial role in various programming tasks, from mathematical computations to data analysis. However, when working with user input or data from external sources, it becomes essential to validate whether the input is a valid floating point number or not. Python provides powerful tools to tackle this challenge, and one such tool is regular expressions.

In this article, we will explore how to use regular expressions in Python to check whether the input is a floating point number or not. Regular expressions, commonly known as regex, offer a concise and flexible way to define patterns and search for matches within text. By leveraging regex, we can build a pattern that precisely matches the format of a floating point number and validate the input accordingly.

In this article, we will explore how to use regular expressions in Python to check whether the input is a floating point number or not. Regular expressions, commonly known as regex, offer a concise and flexible way to define patterns and search for matches within text. By leveraging regex, we can build a pattern that precisely matches the format of a floating point number and validate the input accordingly.

Understanding Floating Point Numbers

Floating point numbers are a data type used to represent real numbers in computer systems. They are called "floating point" because the decimal point can "float" to represent numbers of different magnitudes. In Python, floating point numbers are represented using the float data type.

Floating point numbers can have both integer and fractional parts, and they can be positive or negative. They are typically written in the form m.n, where m represents the integer part and n represents the fractional part. For example, 3.14 and -0.5 are valid floating point numbers.

However, it's important to note that not all decimal representations can be precisely represented as floating point numbers due to the limitations of computer hardware. This can sometimes lead to unexpected results in calculations involving floating point numbers. Therefore, it becomes crucial to validate the input and ensure that it conforms to the expected format.

In the next section, we will explore regular expressions and learn how to use them to check whether the input is a valid floating point number.

Introduction to Regular Expressions

Regular expressions, often abbreviated as regex, are powerful tools for pattern matching and text manipulation. They provide a concise and flexible way to define patterns and search for specific sequences of characters within a string.

In Python, the re module provides functions and methods for working with regular expressions. We can utilize the capabilities of regular expressions to check whether the input is a valid floating point number.

To validate a floating point number using a regular expression, we need to define a pattern that matches the expected format. Here are the key components of the pattern 

  • Optional sign  The number may start with an optional positive (+) or negative (-) sign.

  • Integer part  The number can have an optional integer part, which may consist of one or more digits.

  • Optional decimal point  The number may contain an optional decimal point (.) to separate the integer and fractional parts.

  • Fractional part  The number can have an optional fractional part, which consists of one or more digits.

  • Exponent  The number may have an optional exponent part, denoted by the letter 'e' or 'E' followed by an optional sign and one or more digits.

By constructing a regular expression pattern that encompasses these components, we can effectively check whether the input string matches the pattern of a floating point number.

In the next section, we will delve into the implementation of a Python program that utilizes regular expressions to check for floating point numbers.

Python Program to Check Floating Point Number

To check whether a given input is a floating point number using regular expressions in Python, we can follow these steps 

  • Import the re module  Start by importing the re module, which provides functions and methods for working with regular expressions.

  • Define the regular expression pattern  Create a regular expression pattern that matches the expected format of a floating point number. This pattern will be used to validate the input.

  • Create a function  Define a function, let's call it is_float, that takes an input string as a parameter.

  • Match the pattern  Use the re.match() function to match the input string against the regular expression pattern. This function returns a match object if the pattern matches the string, or None if it doesn't.

  • Check for a match  Use an if statement to check if the match object is not None. If it's not None, it means the input string is a valid floating point number.

  • Return the result  Inside the if statement, return True to indicate that the input is a floating point number. Otherwise, return False.

Now, let's put it all together and write the Python code to check for a floating point number using regular expressions 

import re

def is_float(input_string):
    pattern = r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
    match = re.match(pattern, input_string)
    if match:
        return True
    return False

In the code above, we define the regular expression pattern r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$', which matches the expected format of a floating point number. We use re.match() to match the input string against the pattern and return True if it's a match.

In the next section, we will test our is_float() function with some sample inputs to see how it works.

Testing the Program

Here are some test cases we can try −

  • Test Case 1 

    • Input  "3.14"

    • Expected Output  True

    • Explanation  The input is a valid floating point number.

  • Test Case 2 

    • Input  "-0.5"

    • Expected Output  True

    • Explanation  The input is a valid floating point number.

  • Test Case 3 

    • Input  "10"

    • Expected Output  False

    • Explanation  The input is not a floating point number because it doesn't have a decimal part.

  • Test Case 4 

    • Input  "abc"

    • Expected Output  False

    • Explanation  The input is not a floating point number as it contains non-numeric characters.

  • Test Case 5 

    • Input  "1.23e-4"

    • Expected Output  True

    • Explanation  The input is a valid floating point number in scientific notation.

You can test the program by calling the is_float() function with these inputs and comparing the output with the expected results. If the output matches the expected results for all the test cases, it indicates that the program is functioning correctly.

# Testing the program
print(is_float("3.14"))        # Expected output: True
print(is_float("-0.5"))        # Expected output: True
print(is_float("10"))          # Expected output: False
print(is_float("abc"))         # Expected output: False
print(is_float("1.23e-4"))     # Expected output: True

Conclusion

In this article, we have explored how to use regular expressions in Python to check whether a given input is a floating-point number or not. We learned about the importance of regular expressions in pattern matching and how they can be applied to validate numeric inputs.

We started by understanding the characteristics of floating-point numbers and the common formats in which they can be represented. Then, we dived into the implementation of the is_float() function using regular expressions to check for floating-point numbers. We also discussed the significance of using the re.match() function for exact string matching.

By testing the program with multiple test cases, we ensured its reliability and verified that it correctly identifies floating-point numbers while rejecting invalid inputs.

Updated on: 10-Aug-2023

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements