What is a float in Python?
Short answer: a float is Python's type for numbers with a decimal point, like 19.99, 3.5 or -0.25. You get one when you write a number with a dot, when you divide with /, or when you convert text with float("3.5").
price = 19.99
print(type(price)) # <class 'float'>
print(7 / 2) # 3.5
print(float("3.5") + 1) # 4.5Floats are stored in binary, so some decimals are approximate: 0.1 + 0.2 gives 0.30000000000000004. Round them to show them, and use Decimal for money.
A float is a number with decimals, float() converts text into one and round() hides the tiny binary errors when you show it.
Floats at a glance
| What you want | Code | Result |
|---|---|---|
| Write a float | price = 19.99 | 19.99 |
| Check the type | type(19.99) or isinstance(x, float) | <class 'float'>, True |
| Convert text or an int | float("3.5"), float(7) | 3.5, 7.0 |
| Divide | 7 / 2 | 3.5 (always a float) |
| Divide without decimals | 7 // 2 | 3 |
| Drop the decimals | int(3.99) | 3 |
| Round | round(3.14159, 2) | 3.14 |
| Show with 2 decimals | f"{3.14159:.2f}" | "3.14" |
| Compare safely | math.isclose(0.1 + 0.2, 0.3) | True |
| Exact decimals for money | Decimal("0.1") + Decimal("0.2") | Decimal("0.3") |
| Scientific notation | float("1e3") | 1000.0 |
| Infinity and "not a number" | float("inf"), float("nan") | inf, nan |
How to create a float
Any number with a decimal point is a float, even if the decimals are zero:
a = 3.0
b = -0.25
c = 1e3 # 1000.0, scientific notation
print(type(a), type(c)) # <class 'float'> <class 'float'>Mixing an int and a float gives a float: 5 + 2.0 is 7.0. The / operator always returns a float, even when the division is exact: 10 / 2 is 5.0.
