Tuesday, November 15, 2022

Convert String to float in Python

In this post we’ll see how to convert String to float in Python.

If you have a float represented as String literal then you need to convert it to float value if you have to use it in any arithmetic operation.

For example-

num1 = "50.56"
num2 = 20.45
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 14, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "float") to str

As you can see num1 variable is of type string so Python tries to concatenate num2 to num1 rather than adding them. In such scenario you need to convert string to float.

Python program - convert String to float

To convert a Python String to a float pass that String to float() function which returns a float object constructed from the passed string.

num1 = "50.56"
num2 = 20.45
result = float(num1) + num2
print("Sum is-", result)

Output

Sum is- 71.01

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to float, ValueError is raised. If you are not sure about the passed number it is better to use try and except for exception handling.

For example in the following Python function string ‘abc’ is passed as one of the argument value which results in ValueErorr being raised while converting it.

def add(num1, num2):
  try:
    result = float(num1) + float(num2)
    print("Sum is-", result)
  except ValueError as error:
    print('Error while conversion:', error)

add('abc', 10)

Output

Error while conversion: could not convert string to float: 'abc'

Getting integer part of the decimal number

If there is a decimal number stored as a string and you want only the integer part then directly using int() function results in error. You have to first convert string to float and then to int.

num = "50.56"
# Causes error
int_num = int(num) 
print("Integer part is-", int_num)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    int_num = int(num)
ValueError: invalid literal for int() with base 10: '50.56'

Correct way

num = "50.56"
int_num = int(float(num))
print("Integer part is-", int_num)

Output

Integer part is- 50

That's all for this topic Convert String to float in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Number of Words in a String
  3. Python String isnumeric() Method
  4. Operator Overloading in Python
  5. Check String Empty or Not in Python

You may also like-

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Convert String to float in Java
  6. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  7. intern() Method in Java String
  8. Java Exception Handling Tutorial