Python How to Convert String to Float Easily
Use the built-in
float() function to convert a string to a float in Python like this: float('3.14').Examples
Input'3.14'
Output3.14
Input'0.001'
Output0.001
Input'-123.456'
Output-123.456
How to Think About It
To convert a string to a float, think of the string as a number written in text form. You want to change it into a number your program can use for math. Python has a simple tool called
float() that reads the string and turns it into a decimal number.Algorithm
1
Get the string input that represents a number.2
Use the <code>float()</code> function to convert the string to a floating-point number.3
Return or use the converted float value.Code
python
number_str = '3.14' number_float = float(number_str) print(number_float)
Output
3.14
Dry Run
Let's trace converting the string '3.14' to a float.
1
Input string
number_str = '3.14'
2
Convert to float
number_float = float('3.14') => 3.14
3
Print result
print(3.14) outputs 3.14
| Step | Value |
|---|---|
| Input string | '3.14' |
| After conversion | 3.14 |
| Output | 3.14 |
Why This Works
Step 1: Using float() function
The float() function reads the string and converts it to a decimal number type.
Step 2: String must be a valid number
The string should look like a number (digits, optional decimal point, optional sign) for float() to work.
Step 3: Result is a float type
After conversion, the value is a float number that can be used in math operations.
Alternative Approaches
Using eval() function
python
number_str = '3.14' number_float = eval(number_str) print(number_float)
Works but is unsafe if input is untrusted because eval() runs any code.
Using decimal.Decimal for precise decimal
python
from decimal import Decimal number_str = '3.14' number_decimal = Decimal(number_str) print(number_decimal)
Gives more precise decimal numbers but result is not a float type.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion with float() is a simple parsing operation that runs in constant time.
Space Complexity
No extra memory is needed besides the output float, so space is constant.
Which Approach is Fastest?
float() is the fastest and safest for converting strings to floats compared to alternatives like eval() or Decimal.
| Approach | Time | Space | Best For |
|---|---|---|---|
| float() | O(1) | O(1) | Simple, safe string to float conversion |
| eval() | O(1) | O(1) | Unsafe, runs code, avoid for untrusted input |
| decimal.Decimal | O(1) | O(1) | Precise decimal numbers, not float type |
Always ensure the string looks like a number before converting with
float() to avoid errors.Trying to convert strings with letters or symbols (like '3.14abc') causes errors with
float().