float()
float(x=0.0) Returns:
float · Added in v3.0 · Updated March 13, 2026 · Built-in Functions conversion numbers built-in type
The float() function converts a number or a string representing a number to a floating-point number. It’s one of Python’s fundamental type conversion functions, essential for any numerical computation involving decimals.
Syntax
float(x=0.0)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | int, float, or str | 0.0 | The value to convert to a float. Can be an integer, another float, or a string representation of a number. |
Examples
Converting integers to floats
# Converting integers to floats
print(float(10)) # 10.0
print(float(-5)) # -5.0
print(float(0)) # 0.0
Converting strings to floats
# Converting numeric strings to floats
print(float("3.14")) # 3.14
print(float("-2.5")) # -2.5
print(float("0.0")) # 0.0
# String with whitespace (stripped automatically)
print(float(" 42.5 ")) # 42.5
Special string values
# Special string values
print(float("inf")) # inf
print(float("infinity")) # inf
print(float("-inf")) # -inf
print(float("nan")) # nan
Working with floats directly
# Passing a float returns the same value
print(float(3.14)) # 3.14
print(float(-2.5)) # -2.5
print(float(0.0)) # 0.0
Common Patterns
User input processing
# Converting user input to float for calculations
price = float(input("Enter price: "))
tax = price * 0.08
print(f"Total: {price + tax}")
Default values
# Using float() for default numeric values
def calculate_area(radius, pi=3.14159):
return pi * (radius ** 2)
# Using float() to ensure float division
result = float(10) / 3 # 3.3333333333333335
Numerical computations
# Precision calculations
a = float("0.1")
b = float("0.2")
print(a + b) # 0.30000000000000004 (floating-point precision)
# Scientific notation
print(float("1e-5")) # 1e-05 (0.00001)
print(float("2.5e3")) # 2500.0
Errors
ValueError
float() raises a ValueError when given a non-numeric string:
# These will raise ValueError
float("hello") # ValueError: could not convert string to float: 'hello'
float("3.14.15") # ValueError: could not convert string to float: '3.14.15'
float("") # ValueError: could not convert string to float: ''
float("2 + 3") # ValueError: could not convert string to float: '2 + 3'
TypeError
float() raises a TypeError for unsupported types:
# These will raise TypeError
float([1, 2, 3]) # TypeError: can't convert 'list' object to float
float({"a": 1}) # TypeError: can't convert 'dict' object to float
float(None) # TypeError: can't convert 'NoneType' object to float
See Also
- built-in::int — Convert to integer
- str::str — Convert to string
- built-in::complex — Create a complex number