Skip to content
Related Articles

Related Articles

Convert String to Float in Python

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Sep, 2022
View Discussion
Improve Article
Save Article

Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting the string to float. In Python, we can use float() to convert String to float. and we can use int() to convert String to an integer.

Python Program to Parse a String to a Float

This function is used to convert any data type to a floating-point number.

Syntax of float:

float(x)

The method only accepts one parameter and that is also optional to use. If no argument is passed then the method returns 0.0.

Example 1: Parse a string into a float

In this example, we are converting the string into float.

Python3




string= "3.141"
  
print(string)
print(type(string))
  
# converting string to float
Float = float(string)  
  
print(Float)
print(type(Float))

Output:

3.141
<type 'str'>
3.141
<type 'float'>

Example 2: A string float numeral into float

In this example, we try to convert a string into an integer and then a float. In the output we can see that we can’t convent a string float number into an integer thus, we get a value error.

Python3




string = '55.567'
  
Float = float(int(string))
  
print(type(Float))
print('Float Value =', Float)

Output:

ValueError                                Traceback (most recent call last)
<ipython-input-4-8771a1bc4294> in <module>()
      1 string = '55.567'
      2 
----> 3 Float = float(int(string))
      4 
      5 print(type(Float))

ValueError: invalid literal for int() with base 10: '55.567'

Python Program to Parse a String to Int

This function is used to convert any data type to a integer number.

Syntax of int

int()

Example 1: Parse a string into an integer

In this example, we are converting string into integer.

Python3




string = '55567'
  
Float = int(string)
  
print(type(Float))
print('Float Value =', Float)

Output:

<class 'int'>
55567

Example 2: A string float numeral into an integer

In this example, we try to convert string float into float and then into integer.

Python3




balance_str = "15.0034"
balance_int = int(float(balance_str))
  
# print the type
print(type(balance_int))
  
# print the value
print(balance_int)

Output:

<class 'int'>
15

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!