- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'
Advertisements