Python float() function

The float() function in Python is used to convert a number or a string into a floating-point number (a number that has a decimal point). For example:

x = float(130)
print(x)

x = float("234")
print(x)

x = float(24.5)
print(x)

x = float()
print(x)

The output produced by this program will be:

130.0
234.0
24.5
0.0

Python float() function syntax

The syntax of the float() function in Python is:

float(value)

Python float() function example

Let's create a simple example of the float() function in Python. This program allows the user to enter anything at runtime to convert the input value to a floating-point type value.

print("Enter Anything: ", end="")
val = input()

try:
    fval = float(val)
    print("\nEquivalent floating-point =", fval)
except ValueError:
    print("\nCan not get converted into floating-point type.")

The snapshot given below shows the sample run with user input codescracker:

python float function

Advantages of the float() function in Python

Disadvantages of the float() function in Python

Python Online Test


« Previous Function Next Function »


Liked this post? Share it!