The float() function returns a floating-point number from a number (integer) or a string. It’s a basic inbuilt function in python, you don’t need to import any module.
Float() function used for converts the specified value into a floating-point number.
Syntax
float(value)
Return value from float() function
- Equivalent floating-point number if an argument is passed
- 0.0 if no arguments passed
OverflowError
exception if the argument is outside the range of Python float
Example: Python float function
1. Convert a string into a floating-point number:
x = float("3.500") print(type(x)) print(x)
Output:
2. Convert a Number into a floating-point number:
x = float(3.500) print(type(x)) print(x)
More Examples:-
Look at the below code program of various examples and the working of the float() method.
# for integers (Numbers) print(float(21.89)) # for floating point numbers print(float(8)) # for integer type strings print(float("47")) # for floating type strings print(float("-77.56")) # for string floats with whitespaces print(float(" -34.75 \n")) # for inf/infinity print(float("InF")) print(float("InFiNiTy")) # for NaN print(float("nan")) print(float("NaN")) # Error is generated at last print(float("EyeHunts"))
Output:
21.89
8.0
47.0
-77.56
-34.75
inf
inf
nan
nan
Last line Error: could not convert string to float
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in PyCharm 2019.3 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python Programs are in Python 3, so it may change its different from python 2 or upgraded versions.