Python built-in Method - float()

The float() method is a built-in function in Python that converts a given argument to a floating-point number. The argument can be a number, a string, or any object that defines the __float__() method.

Here is the syntax for float() method:

float(x)
Source:‮w‬ww.theitroad.com

where x is the value to be converted to a float.

Here are some examples of how to use float():

x = 3
y = 4.5
z = "7.8"

# convert integers and floats to floats
a = float(x)
b = float(y)

# convert string to float
c = float(z)

print(a)  # 3.0
print(b)  # 4.5
print(c)  # 7.8

In this example, we use the float() method to convert integers, floats, and strings to floats. The output of the code is 3.0, 4.5, and 7.8, respectively.

Note that if the argument passed to float() is a string that cannot be converted to a float, a ValueError will be raised. For example:

s = "hello"
float(s)  # raises ValueError: could not convert string to float: 'hello'

Also note that the float() method can be used to convert any object that defines the __float__() method to a float. For example:

class MyFloat:
    def __float__(self):
        return 3.14

x = MyFloat()
print(float(x))  # 3.14