Tutorial Study Image

Python float()

The float() method returns the corresponding floating-point number from a given number or a string.


float([x]) #Where x can be a number or string that needs to convert
 

float() Parameters:

It takes a single parameter, a number, or string that needs to return a floating-point number

Parameter Description Required / Optional
Float  Used as a floating number Optional
Integer Used as an integer number Optional
String It contains decimal numbers. Leading and trailing whitespaces are removed. Optional use of "+", "-" signs. Could contain NaN, Infinity, inf (lowercase or uppercase). Optional

float() Return Value

Input Return Value
If an argument Equivalent floating-point number
If no argument 0.0 
The argument is outside the range of Python float OverflowError exception 

Examples of float() method in Python

Example 1: Working of float()in Python?


# for integers
print(float(20))

# for floats
print(float(12.33))

# for string floats
print(float("-15.34"))

# for string floats with whitespaces
print(float("     -32.25\n"))

# string float error
print(float("abcd"))
 

Output:

20.0
13.33
-15.34
-32.25
ValueError: could not convert string to float: 'abcd'

Example 2: float() for infinity and Nan(Not a number)?


# for NaN
print(float("nan"))
print(float("NaN"))

# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))
 

Output:


nan
nan
inf
inf
inf
inf