The float([x]) built-in function constructs a floating-point number from an integer, float, or formatted numeric string.
IEEE 754 Double Precision: In CPython, float is implemented as a 64-bit IEEE 754 double-precision number with 53 bits of precision. It parses standard decimal strings, scientific exponential notation (e.g. "1e-3"), and case-insensitive special values like "inf" and "nan". Custom classes can support float() by implementing the __float__() dunder method. To convert values to integers or booleans, see companion constructors int() and bool().
The float() constructor accepts zero or one argument:
# Formal syntax of built-in float()
float_val = float([x])
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
x |
int, float, str, or __float__() object |
Optional value to convert. If omitted, returns 0.0. |
| Return Value | float |
A 64-bit IEEE 754 floating-point number. |
float() converts integers to decimals and parses numeric strings cleanly, tolerating surrounding whitespace:
# 1. Zero-argument and integer conversions
print("float(): ", float()) # 0.0
print("float(5): ", float(5)) # 5.0
print("float(0): ", float(0)) # 0.0
# 2. String conversions with whitespace tolerance
print("float('34.5'): ", float("34.5")) # 34.5
print("float(' 45.8 '):", float(" 45.8 ")) # 45.8 (strips leading/trailing spaces)
# 3. Scientific notation parsing
print("float('1e-3'): ", float("1e-3")) # 0.001
print("float('2.5e4'): ", float("2.5e4")) # 25000.0
Output:
float(): 0.0
float(5): 5.0
float(0): 0.0
float('34.5'): 34.5
float(' 45.8 '): 45.8
float('1e-3'): 0.001
float('2.5e4'): 25000.0
Python's float() constructor recognizes case-insensitive representations of mathematical infinity and undefined numeric values:
import math
# Case-insensitive special IEEE 754 representations
pos_inf = float("inf")
neg_inf = float("-Infinity")
nan_val = float("nan")
print("Positive Infinity: ", pos_inf)
print("Negative Infinity: ", neg_inf)
print("Not a Number (NaN):", nan_val)
# Checking special states
print("math.isinf(pos_inf):", math.isinf(pos_inf))
print("math.isnan(nan_val):", math.isnan(nan_val))
# Crucial NaN property: NaN is never equal to anything, including itself!
print("nan == nan: ", nan_val == nan_val) # False!
Output:
Positive Infinity: inf
Negative Infinity: -inf
Not a Number (NaN): nan
math.isinf(pos_inf): True
math.isnan(nan_val): True
nan == nan: False
math.isnan(x) rather than equality (x == float('nan')), because the IEEE 754 standard defines NaN as non-equal to every value, including itself.
User-defined classes can integrate with the float() constructor by defining the __float__() dunder method:
# Custom classes implementing __float__() and __index__()
class TemperatureSensor:
def __init__(self, celsius: float):
self.celsius = celsius
def __float__(self) -> float:
# Returns temperature as standard float
return float(self.celsius)
sensor = TemperatureSensor(23.75)
print("Type of sensor: ", type(sensor))
print("float(sensor) reading:", float(sensor))
Output:
Type of sensor:
float(sensor) reading: 23.75
When strings contain invalid non-numeric characters, float() raises a ValueError:
# Pitfall 1: ValueError on malformed numeric strings
try:
float("abc45")
except ValueError as err:
print("ValueError caught:", err)
# Pitfall 2: Binary floating-point representation limits
print("0.1 + 0.2 == 0.3: ", 0.1 + 0.2 == 0.3) # False!
print("0.1 + 0.2 actual: ", 0.1 + 0.2) # 0.30000000000000004
import math
print("math.isclose(): ", math.isclose(0.1 + 0.2, 0.3)) # True
Output:
ValueError caught: could not convert string to float: 'abc45'
0.1 + 0.2 == 0.3: False
0.1 + 0.2 actual: 0.30000000000000004
math.isclose(): True
Below are real-world recipes utilizing float() for safe user input parsing and currency calculations:
# Recipe A: Safe user input float parser with fallback
def safe_parse_float(raw: str, default: float = 0.0) -> float:
try:
# Strip currency symbols and whitespace
clean_text = raw.replace('USD', '').replace('$', '').replace(',', '').strip()
return float(clean_text)
except (ValueError, TypeError, AttributeError):
return default
print("Parse ' USD 1,249.50 ':", safe_parse_float(" USD 1,249.50 "))
print("Parse 'invalid_str': ", safe_parse_float("invalid_str", default=-1.0))
print("Parse None: ", safe_parse_float(None))
# Recipe B: Financial currency rounding vs Decimal
unit_price = float("19.99")
quantity = 3
subtotal = round(unit_price * quantity, 2)
print("Calculated subtotal:", subtotal)
Output:
Parse ' USD 1,249.50 ': 1249.5
Parse 'invalid_str': -1.0
Parse None: 0.0
Calculated subtotal: 59.97
0.1 cannot be represented exactly in binary, causing calculations like 0.1 + 0.2 to equal 0.30000000000000004. Use math.isclose() for equality comparisons."1,200.50" raise ValueError unless cleaned beforehand.3 + 4j cannot be converted directly to float; access z.real or compute vector magnitude with abs(z) instead.Practice string-to-float conversions, IEEE 754 special values, and safe parsers in our companion Jupyter Notebook:
Explore interactive code cells, benchmark float parsing speed, inspect IEEE 754 precision boundaries, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify float() mechanics:
def test_float_mechanics():
# 1. Basic conversions
assert float() == 0.0
assert float(5) == 5.0
assert float("3.14") == 3.14
assert float(" 10.5 ") == 10.5
assert float("1e-2") == 0.01
# 2. Special values
import math
assert math.isinf(float("inf"))
assert math.isnan(float("nan"))
# 3. Custom __float__
class Measure:
def __float__(self):
return 42.5
assert float(Measure()) == 42.5
print("All float() unit assertions passed! 100% verified.")
test_float_mechanics()
Output:
All float() unit assertions passed! 100% verified.
Converts numbers or strings into integer values.
Evaluates truth value testing and converts objects to booleans.
Rounds floating-point numbers to specified precision.
Calculates the non-negative magnitude of a number or complex vector.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.