How to Convert string to float in Python
Published on Aug. 22, 2023, 12:16 p.m.
To convert a string to a float in Python, you can use the float()
function, which is a built-in function in Python. The float()
function takes a string or a number as input and returns a floating-point number. Here’s an example:
my_string = "3.14"
my_float = float(my_string)
print(my_float) # Output: 3.14
In this example, we define a string my_string
containing the value 3.14
. We use the float()
function to convert the string into a floating-point number called my_float
. The resulting value in my_float
is equivalent to the original value in my_string
, but in floating-point format.
If the string cannot be converted to a float (for example, if it contains non-numeric characters), the float()
function will raise a ValueError. You can catch this exception using a try-except block to handle the error gracefully.
In general, converting a string to a float can be useful when you need to perform mathematical calculations involving decimal numbers or when passing numeric values as arguments to functions that expect floating-point numbers.