2 ways to convert a string to float in Python:
- Using float() Method
- Using numpy.float64() Method
Method 1: Using float() Method
Example 1: Basic Usage
# String representation of a floating-point number
string_value = "21.53436"
print("======= Before conversion =======")
print(string_value)
print(type(string_value))
# Convert string to float
float_value = float(string_value)
print("======= After conversion =======")
print(float_value )
print(type(float_value ))
Output
======= Before conversion =======
21.53436
<class 'str'>
======= After conversion =======
21.53436
<class 'float'>
Example 2: Formatting a Floating-Point Number to Two Decimal Places
string_value = "21.53436"
float_value = float(string_value)
formatted_float_value = "{:.2f}".format(float_value)
print("======= After conversion =======")
float_value = float(formatted_float_value)
print(float_value)
print(type(float_value))
Output
21.53
<class 'float'>
Example 3: ValueError: could not convert string to float
string_value = "21.53aw6"
float_value = float(string_value)
print("======= After conversion =======")
print(float_value )
print(type(float_value ))
Output
ValueError: could not convert string to float: '21.53aw6'
Above code raises a ValueError because the string does not represent a valid floating-point number.
To prevent such errors, implement exception handling to catch ValueError exceptions.
string_value = "21.53aw6"
try:
float_value = float(string_value)
print("======= After conversion =======")
print(float_value)
print(type(float_value))
except ValueError:
print("The string does not represent a valid floating-point number.")
Output
The string does not represent a valid floating-point number.
Method 2: Using numpy.float64() Method
import numpy as np
string_value = "21.53436"
print("======= Before conversion =======")
print(string_value)
print(type(string_value))
float_value = np.float64(string_value)
print("======= After conversion =======")
print(float_value )
print(type(float_value ))
Output
======= Before conversion =======
21.53436
<class 'str'>
======= After conversion =======
21.53436
<class 'numpy.float64'>
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.