float() parses strings containing decimal numbers, scientific notation, and even the special values 'inf' and 'nan' (case-insensitive). Passed an int, it simply adds a fractional part of .0. Like all binary floating-point implementations, Python floats can't represent every decimal value exactly, which is why adding 0.1 and 0.2 famously produces a result like 0.30000000000000004 instead of a clean 0.3.
1Understanding float()
float() parses strings containing decimal numbers, scientific notation, and even the special values 'inf' and 'nan' (case-insensitive). Passed an int, it simply adds a fractional part of .0. Like all binary floating-point implementations, Python floats can't represent every decimal value exactly, which is why adding 0.1 and 0.2 famously produces a result like 0.30000000000000004 instead of a clean 0.3.
Never compare floats with == for 'closeness' — use math.isclose(a, b) instead, since rounding error accumulates in almost every non-trivial floating-point calculation.
print(float("3.14"))
print(float("1e3"))
print(float(7))2Practical Example
Here is a real-world application of float() showing how it is used in production Python code.
price_text = "19.99"
tax_rate = 0.08
price = float(price_text)
total = price * (1 + tax_rate)
print(f"Total: ${total:.2f}")3Best Practices
Follow these guidelines when working with float():
1. Use the decimal module instead of float for money or anywhere exact decimal precision matters
2. Use math.isclose() rather than == when comparing computed float results
3. Validate/catch ValueError when converting user input with float(), the same as with int()
Tip: Never compare floats with == for 'closeness' — use math.isclose(a, b) instead, since rounding error accumulates in almost every non-trivial floating-point calculation.
print(float("3.14"))
print(float("1e3"))
print(float(7))