float()
Python · Variables & Data Types
Theory
float() builds a floating-point number from another value. Integers become their decimal version (float(7) is 7.0), and strings are parsed if they look like a number: '19.99', ' 3.5 ' with spaces, scientific notation like '1e3' (which is 1000.0), and even the special words 'inf' and 'nan'. Text that is not numeric, such as 'abc' or '1,200' with a comma, raises ValueError.
Remember what a float really is: a 64-bit binary approximation. float('19.99') stores the closest binary value to 19.99, which is why arithmetic can show tiny errors and why == comparisons on floats are risky. When converting prices from text, clean the string first (remove commas and the rupee sign with replace()) and decide where rounding should happen.
Why we use it
Prices, percentages, ratings and measurements usually have decimals and often arrive as text from CSV files or web forms. float() turns that text into a number you can sum, average and compare.
When to use it
Use float() for measurement-like values where small rounding is acceptable. For exact currency, use decimal.Decimal('19.99'). Strip thousands separators before converting: float('1,200'.replace(',', '')).
How it works
- float(value) is called
- Is value already an int? Yes: Return the same number as a float, 7 -> 7.0. No: Treat it as text.
- Strip surrounding whitespace from the text
- Does it look like a number, e.g. 19.99, 1e3, inf? Yes: Convert to the nearest binary float. No: Raise ValueError.
- e.g. float('19.99') returns 19.99 of type float
Syntax
float(value)Example
price = float("19.99")
print(price, type(price))Key points
- Accepts integers, numeric strings, and scientific notation like "1e3"
- Raises a ValueError on non-numeric text like float("abc")
- Commas break it: clean '1,200' to '1200' first
- The result is a binary approximation, so avoid == on floats
- float('inf') and float('nan') create the special infinity and not-a-number values