float() in Python


Float method is part of python standard library which converts a number or a string containing numbers to a float data type. There are following rules when a string is considered to be valid for converting it to a float.

  • The string must have only numbers in it.

  • Mathematical operators between the numbers can also be used.

  • The string can represent NaN or inf

  • The white spaces at the beginning and end are always ignored.

Example

The below program indicates how different values are returned when float function is applied.

n = 89
print(type(n))
f = float(n)
print(type(f))
print("input",7," with float function becomes ",float(7))
print("input",-21.6," with float function becomes ",float(-21.6))
print("input NaN, with float function becomes ",float("NaN"))
print("input InF, with float function becomes ",float("InF"))

Output

Running the above code gives us the following result −

<class 'int'>
<class 'float'>
input 7 with float function becomes 7.0
input -21.6 with float function becomes -21.6
input NaN, with float function becomes nan
input InF, with float function becomes inf

Passing a stream without having any numeric values throws error.

Example

print("input Tutorials, with float function becomes ",float("Tutorials"))

Output

Running the above code gives us the following result −

Traceback (most recent call last):
   File "C:/xxx.py", line 18, in
      print("input Tutorials, with float function becomes ",float("Tutorials"))
ValueError: could not convert string to float: 'Tutorials'

Updated on: 07-Aug-2019

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements