Convert String to Float in Python
The goal of converting a string to a float in Python is to ensure that numeric text, such as “33.28”, can be used in mathematical operations. For example, if a variable contains the value “33.28”, we may want to convert it to a float to perform operations like addition or division. Let’s explore different methods to do this efficiently.
Using float()
float() function is an efficient way to convert a string into a floating-point number. As a built-in function, it returns a value of type float and works best with well-formatted numeric strings. However, if the input string is not a valid representation of a float, it raises a ValueError.
[GFGTABS]
a = "33.28"
b = float(a)
print(type(b), b)
[/GFGTABS]
<class 'float'> 33.28
Using decimal.Decimal
Decimal class from Python’s decimal module provides precise decimal arithmetic, making it ideal for situations where accuracy is important , such as financial calculations. It converts a string into a Decimal object, effectively avoiding common floating-point rounding errors.
[GFGTABS]
from decimal import Decimal
a = "33.28"
b = float(Decimal(a))
print(type(b), b)
[/GFGTABS]
<class 'float'> 33.28
Using eval()
eval() function reads and runs a string as a Python expression. It can turn a numeric string like “33.28” into a float. However, it’s risky to use with untrusted input because it can run harmful code. It’s best used only in safe and controlled situations.
[GFGTABS]
a = "33.28"
b = eval(a)
print(type(b), b)
[/GFGTABS]
<class 'float'> 33.28
Using ast.literal_eval()
ast.literal_eval() function safely evaluates strings that contain Python literals, such as numbers or lists. It can securely convert a numeric string to a float. Unlike eval(), it doesn’t run any code, making it a safer option for handling user input.
[GFGTABS]
import ast
a = "33.28"
b = ast.literal_eval(a)
print(type(b), b)
[/GFGTABS]
<class 'float'> 33.28
Related Articles: