Monday 29 May 2023

Convert a string to float in Python

Using float() function, you can convert a string to a float in Python.

 

Example

float_var = float(input_str)

 

float_to_int.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

float_var = float(input_str)
print('float_var : ', float_var, " type : ", type(float_var))

 

Output

Enter a string 12.34
input_str :  12.34  type :  <class 'str'>
float_var :  12.34  type :  <class 'float'>

 

If the input_str contains any non-numeric characters, you will endup in ValueError like below.

Enter a string 12.aw2
input_str :  12.aw2  type :  <class 'str'>
Traceback (most recent call last):
  File "/Users/Shared/PycharmProjects/python/python-core/1.introduction/string_to_float.py", line 4, in <module>
    float_var = float(input_str)
ValueError: could not convert string to float: '12.aw2'

Process finished with exit code 1

We can handle above error situations using try-except block.


string_to_float.py

input_str = input('Enter a string ')
print('input_str : ', input_str, " type : ", type(input_str))

try:
    float_var = float(input_str)
    print('float_var : ', float_var, " type : ", type(float_var))
except ValueError as ve:
    print("input string contain non numeric characters. error : ", ve)

Output

Enter a string 12.aw2
input_str :  12.aw2  type :  <class 'str'>
input string contain non numeric characters. error :  could not convert string to float: '12.aw2'



Previous                                                 Next                                                 Home

No comments:

Post a Comment