In Python, float() is a built-in function used to convert strings, integers, or other numeric types to floating-point numbers.

Function Syntax

float(x)

Parameters:

  • x: The object to convert to a floating-point number. Can be a string, integer, float, or other numeric type.

If the parameter is a string, it must contain decimal digits and may optionally have a sign or leading whitespace.

float() Function Examples

Convert a string to a float:

str_num = "3.14"
float_num = float(str_num)
print(float_num)  # Output: 3.14

In addition to converting strings, the float() function can also convert other numeric types to floating-point numbers:

# Convert integer to float
int_num = 42
float_num = float(int_num)
print(float_num)  # Output: 42.0

# Convert other numeric types to float
complex_num = 1 + 2j
float_num = float(complex_num)  # Raises TypeError exception because complex numbers cannot be converted to floats
print(float_num)

Infinity

The parameter can also be a string representing positive or negative infinity. For example, inf, Inf, INFINITY, iNfINity can all represent positive infinity.

float('-Infinity')  # Negative infinity

__float__()

If the parameter is an object, float(x) calls x.__float__(). If x doesn't define __float__(), it calls __index__():

class c1:
    def __float__(self):
        return 0.01

class c2:
    def __index__(self):
        return 0

x1 = c1()
x2 = c2()

print(float(x1), float(x2))  # Output: 0.01 0.0