How to Convert a String to a Float Decimal in Python

AuthorSumit Dey Sarkar

Pubish Date22 Apr 2023

categoryPython

In this tutorial we will learn how to convert a string to a float decimal in Python.

 

How to Convert a String to a Float Decimal in Python

Using the built-in float() method in Python, you can change a string into a floating-point decimal number. Here's an example:

string_num = "3.14159"
float_num = float(string_num)
print(float_num)

In this example, we first define a string string_num containing the value "3.14159". We then call the float() function and pass the string as an argument. The function returns a float decimal value, which we assign to the variable float_num. Finally, we print the value of float_num.

 

Output:

3.14159

 

A ValueError exception will be generated if the string cannot be transformed into a float. For example:

string_num = "not a number"
float_num = float(string_num)

 

Output:

ValueError: could not convert string to float: 'not a number'

 

Comments 0

Leave a comment