Home »
Python »
Python Reference »
Python Built-in Functions
Python float() Function: Use, Syntax, and Examples
By IncludeHelp Last updated : December 07, 2024
Python float() function
The float() function is a library function in Python, it is used to get a float value from a given number or a string. It accepts either a string (that should contain a number) or a number and returns a float value.
Consider the below example with sample input/output values:
Input:
val1 = "10.23"
val2 = "10"
val3 = 10
print(float(val1))
print(float(val2))
print(float(val3))
Output:
10.23
10.0
10.0
Syntax
The following is the syntax of float() function:
float(value)
Parameter(s):
The following are the parameter(s):
- value – string or number to be converted into float.
Return Value
The return type of float() function is <type 'float'>, it returns a float value.
Python float() Example 1: String and integer to float
# python code to demonstrate an example
# of float() function
print(float("10.23")) # will return 10.23
print(float("10")) # will return 10.0
print(float(10)) # will return 10.0
print(float(10.23)) # will return 10.23
Output
10.23
10.0
10.0
10.23
Python float() Example 2: Input a float value
# Input float value
# Input
height = float(input("Enter height: "))
# Print
print("height:", height)
Output
Enter height: 160.5
height: 160.5
Python float() Example 3: ValueError
If the given value is not a valid float or integer, the function returns a ValueError.
float# ValueError
x = float("weight 160.5") # ValueError
print(x)
Output
Traceback (most recent call last):
File "/home/main.py", line 3, in <module>
x = float("weight 160.5") # ValueError
ValueError: could not convert string to float: 'weight 160.5'