The float()
function in Python is a built-in function that is used to convert a number or a string to a floating-point number. It is used to convert an object to a floating-point number. If the argument passed to the function is a string, it must contain a valid number representation. If the argument is not a string or a number, the function raises a TypeError
exception.
Syntax
float(x)
Parameters
x
– The number or string to be converted to a floating-point number
Return Value
The float()
function returns a floating-point number representation of the argument passed to it.
Examples
Example 1: Converting a Number to a Floating-Point Number
number = 10 result = float(number) print(result)
Output:
10.0
In this example, the variable number
is assigned the value 10. The float()
function is then used to convert this number to a floating-point number, and the result is stored in the variable result
. The value of result
is then printed, and it is a floating-point number representation of the original number.
Example 2: Converting a String to a Floating-Point Number
string = "10.5" result = float(string) print(result)
Output:
10.5
In this example, the variable string
is assigned a string representation of a floating-point number. The float()
function is then used to convert this string to a floating-point number, and the result is stored in the variable result
. The value of result
is then printed, and it is a floating-point number representation of the original string.
Example 3: Converting an Object to a Floating-Point Number
class MyNumber: def __init__(self, value): self.value = value def float(self): return float(self.value) my_number = MyNumber(10) result = float(my_number) print(result)
Output:
10.0
In this example, a custom class MyNumber
is defined, which has a __float__()
method. This method is used to convert the value stored in an instance of the class to a floating-point number. An instance of the class MyNumber
is created with the value 10, and this instance is passed to the float()
function. The float()
function then calls the float()
method of the class to convert the value to a floating-point number, and the result is stored in the variable result
. The value of result
is then printed, and it is a floating-point number representation of the original value stored in the instance of the class.
Use Cases
The float()
function has various use cases in Python programming, some of which are:
- Converting a number to a floating-point number
- Converting a string representation of a number to a floating-point number
- Converting an object to a floating-point number
The float()
function is commonly used when working with mathematical operations in Python, as many mathematical operations require floating-point numbers as input.