This tutorial explains the Python float() method that takes a number or string and returns a floating-point value. If it is not able to convert the string to float, then it raises the ValueError. Let’s try to understand how to use it with the help of simple examples.
1. float() syntax
2. float() with +ve numbers
3. float() with -ve numbers
4. float() with strings of numbers
5. float() with invalid inputs
Let’s now go through each of the sections one by one.
Also Check: Generate Float Range in Python
Python Float() Explained with Several Examples
Float() is a built-in Python function that converts a number or a string to a float value and returns the result. If it fails for any invalid input, then an appropriate exception occurs.
Let’s now see the details and check out how can we use it.
The float() Syntax
The basic syntax to use Python float() is as follows:
float([ A number or string])
Parameter | Description |
---|---|
x (required) | The value or expression to convert into a floating-point number. It can be an integer, a string representing a floating-point number, or any valid numeric expression. |
Return Value | Description |
---|---|
Floating-point | The float() function returns the floating-point representation of the input value. If the input is already a floating-point number, it returns the same value. If the input is a string containing a valid floating-point representation, it converts and returns the equivalent floating-point number. If the input is a numeric expression, it calculates the result and returns it as a floating-point number. |
Possible Errors | Description |
---|---|
ValueError | If the input x is not a valid numeric string or expression, the float() function raises a ValueError . For example, passing a string that contains non-numeric characters or an empty string would result in this error. |
OverflowError | In rare cases, when attempting to convert extremely large or small numbers to float, an OverflowError might be raised. This occurs when the number is outside the range of representable floating-point values. It’s less common but still a possible error. |
Python float() Examples
Here, we are using float() to address different use cases. Hope, these should help you with this function from all corners.
1- Pass a mix of +ve regular and decimal numbers
In this example, we’ll provide a set of +ve values in the float() call. So, it should simply convert them to an equivalent floating-point number. Let’s see.
""" Desc: Python example to demonstrate float() function """ # Test Input testInput = [0, 1, 10000, 0.0, 1.1001, 1.000000000000001, 1.0000000000000001, 1.0000] for eachItem in testInput: print("float({}) = {}".format(eachItem, float(eachItem)))
After executing the snippet shown above, you see the following result:
float(0) = 0.0 float(1) = 1.0 float(10000) = 10000.0 float(0.0) = 0.0 float(1.1001) = 1.1001 float(1.000000000000001) = 1.000000000000001 float(1.0) = 1.0 float(1.0) = 1.0 float(1.0) = 1.0
You can see that the number 1.0000000000000001 got truncated to 1.0. It’s none other than Python which has rounded the float value. If you store it to a variable, then even it reduces to 1.0.
2- Pass the same set of numbers but with a -ve sign
This time, we’ll execute float() on a group of -ve values. We’ve stored all test numbers in a list to run our tests.
""" Desc: Python example to demonstrate float() function on -ve numbers """ # Test Input testInput = [-1, -10000, -0.0, -1.1001, -1.000000000000001, -1.0000000000000001, -1.0000] for eachItem in testInput: print("float({}) = {}".format(eachItem, float(eachItem)))
This code would give you the following result:
float(-1) = -1.0 float(-10000) = -10000.0 float(-0.0) = -0.0 float(-1.1001) = -1.1001 float(-1.000000000000001) = -1.000000000000001 float(-1.0) = -1.0 float(-1.0) = -1.0
3- Testing float() with different strings of numbers
When you send a number in text form, float() translates the value to Python float type.
To test this, we’ve taken a list of strings containing both +ve and -ve numbers.
""" Desc: Python example to demonstrate float() function on strings """ # Test Input testInput = ["-1", "-10000", "0.0", "1.1001", "1.000000000000001", "-1.0000000000000001", " 1.0000 "] for eachItem in testInput: print("float({}) = {}".format(eachItem, float(eachItem)))
After running this code, you will get the following output:
float('-1') = -1.0 float('-10000') = -10000.0 float('0.0') = 0.0 float('1.1001') = 1.1001 float('1.000000000000001') = 1.000000000000001 float('-1.0000000000000001') = -1.0 float(' 1.0000 ') = 1.0
You can now go through the result and understand our test input list included multiple values. And, the float() function successfully returned the correct float values for each of them. Also, it removed the spaces from the start and end of the string as given in the last element of the list.
Python float() function also handles the following keywords both in lower and upper cases very well.
- NaN,
- Infinity,
- Inf.
Let’s check this fact with an example.
""" Desc: Python float() exmaple for NaN, Infinity, inf """ # Test Input testInput = ["nan", "NaN", "inf", "InF", "InFiNiTy", "infinity"] # Let's test float() for eachItem in testInput: if isinstance(eachItem, str): print('float ( "{}" ) => {}'.format(eachItem, float(eachItem))) else: print("float ( {} ) => {}".format(eachItem, float(eachItem)))
After running the given code, the output is:
float ( "nan" ) => nan float ( "NaN" ) => nan float ( "inf" ) => inf float ( "InF" ) => inf float ( "InFiNiTy" ) => inf float ( "infinity" ) => inf
4. Pass wrong values to the float() function
Finally, we’ll test the Python float() function by passing the wrong parameters. And hopefully, we’ll try to cover all the errors or exceptions it can throw.
Let’s see how the float() function handles the wrong parameters.
# Description: Handling wrong values with the Python float() function # Define a list of wrong values wrong_values = [None, "Python", "0,1", "0 1", 1+2j] # Initialize an index for iteration index = 0 # Continue until the end of the list is reached while index < len(wrong_values): wrong_value = wrong_values[index] try: # Attempt to convert to float; if it's not a string, this will raise a TypeError result = float(wrong_value) print(f"float({wrong_value}) = {result}") except ValueError as ex: if isinstance(wrong_value, str): print(f"float('{wrong_value}') = ValueError: {ex}") else: print(f"float({wrong_value}) = ValueError: {ex}") except TypeError as ex: print(f"float({wrong_value}) = TypeError: {ex}") # Increment the index for the next iteration index += 1 # Check for division by zero try: result = float(1/0) print(f"float(1/0) = {result}") except ZeroDivisionError as ex: print(f"float(1/0) = ZeroDivisionError: {ex}") except ValueError as ex: print(f"float(1/0) = ValueError: {ex}")
Since this program raises exceptions for every invalid input, we used the Python try-except block to catch and print errors. After running the given snippet, you see the following output:
float(None) = TypeError: float() argument must be a string or a real number, not 'NoneType' float('Python') = ValueError: could not convert string to float: 'Python' float('0,1') = ValueError: could not convert string to float: '0,1' float('0 1') = ValueError: could not convert string to float: '0 1' float((1+2j)) = TypeError: float() argument must be a string or a real number, not 'complex' float(1/0) = ZeroDivisionError: division by zero
We hope that after wrapping up this tutorial, you will feel comfortable using the Python float() method. However, you may practice more with examples to gain confidence.
Also, to learn Python from scratch to depth, read our step-by-step Python tutorial.