Table of Contents
In this tutorial, we will learn about the Python float() method with the help of examples.
The float()
method returns a floating point number from a number or a string.
Example
int_number = 25 # convert int to float float_number = float(int_number) print(float_number) # Output: 25.0
1. float() Syntax
The syntax for float()
is:
float([x])
2. float() Parameters
The float()
method takes a single parameter:
- x (Optional) – number or string that needs to be converted to floating point number
If it’s a string, the string should contain decimal points
Parameter Type | Usage |
---|---|
Float number | Use as a floating number |
Integer | Use as an integer |
String | Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of “+”, “-” signs. Could contain NaN , Infinity , inf (lowercase or uppercase). |
3. float() Return Value
The float()
method returns:
- Equivalent floating point number if an argument is passed
- 0.0 if no arguments passed
OverflowError
exception if the argument is outside the range of Python float
4. Example 1: How float() works in Python?
# for integers print(float(10)) # for floats print(float(11.22)) # for string floats print(float("-13.33")) # for string floats with whitespaces print(float(" -24.45\n")) # string float error print(float("abc"))
Output
10.0 11.22 -13.33 -24.45 ValueError: could not convert string to float: 'abc'
5. Example 2: float() for infinity and Nan(Not a number)?
# for NaN print(float("nan")) print(float("NaN")) # for inf/infinity print(float("inf")) print(float("InF")) print(float("InFiNiTy")) print(float("infinity"))
Output
nan nan inf inf inf inf
Related posts:
Python set()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Convert Decimal to Binary Using Recursion
Python property()
Python Program to Return Multiple Values From a Function
Python Program to Sort Words in Alphabetic Order
Python String format_map()
Python Program to Get the File Name From the File Path
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Operator Overloading
Python Program to Check If a String Is a Number (Float)
Python exec()
Python List index()
Python int()
Python String isidentifier()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Randomly Select an Element From the List
Python ascii()
Python Set symmetric_difference_update()
Python String rpartition()
Python sleep()
Python Program to Parse a String to a Float or Int
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Dictionary
Python Program to Find Factorial of Number Using Recursion
Python List reverse()
Python str()
Python open()
Python Program to Find the Square Root
Python Program to Count the Number of Digits Present In a Number
Python zip()
Python List copy()