The Wayback Machine - https://web.archive.org/web/20240915172649/https://www.geeksforgeeks.org/float-in-python/
Open In App

float() in Python

Last Updated : 10 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python float() function is used to return a floating-point number from a number or a string representation of a numeric value.

Example:

Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value.

Python3




# convert integer value to float
num = float(10)
print(num)


Output:

10.0

Python float() Function Syntax

The float() function in Python has the following syntax.

Syntax:  float(x)

Parameter x: x is optional & can be:

  • any number or number in form of string, ex,: “10.5”
  • inf or infinity, NaN (any cases)

Return: Float Value

Values that the Python float() method can return depending upon the argument passed

  • If an argument is passed, then the equivalent floating-point number is returned.
  • If no argument is passed then the method returns 0.0.
  • If any string is passed that is not a decimal point number or does not match any cases mentioned above then an error will be raised.
  • If a number is passed outside the range of Python float then OverflowError is generated.

float() in Python Example

Now, let us see a few examples of float() in Python.

Python float() Working

Let us see how the Python float() function works, In this example, we passed different datatype values to the float() function as parameters to see how it works.

Python3




# Python program to illustrate
# Various examples and working of float()
# for integers
print(float(21.89))
 
# for floating point numbers
print(float(8))
 
# for integer type strings
print(float("23"))
 
# for floating type strings
print(float("-16.54"))
 
# for string floats with whitespaces
print(float("     -24.45   \n"))
 
# for inf/infinity
print(float("InF"))
print(float("InFiNiTy"))
 
# for NaN
print(float("nan"))
print(float("NaN"))


Output: 

21.89
8.0
23.0
-16.54
-24.45
inf
inf
nan
nan

Integer Datatype

In this example, we passed an integer type value to the float() function.

Python3




# python code to convert int
# float
number = 90
result = float(number)
 
print(result)


Output:

90.0

Infinity and Nan

In this example, we passed infinite and NaN values to the float() function and then print their equivalent float values.

Python3




# Python program to illustrate
# Various examples and working of float()
 
# for inf/infinity
print(float("InF"))
print(float("InFiNiTy"))
 
# for NaN
print(float("nan"))
print(float("NaN"))


Output:

inf
inf
nan
nan

String Datatype

In this example, we try to print the equivalent float values of the Python String datatype. We will be passing a number as a String value.

Python3




# python code to convert string
# to float
string = "90"
result1 = float(string)
 
# for floating type strings
float_string = "-16.54"
result2 = float(float_string)
 
print(result1)
print(result2)


Output:

90.0
-16.54

Python float() Exceptions and Errors

Sometimes the float() function in Python may not be compatible with all the datatypes. In this case, it may raise an exception or generate an error.

Python float() exception

Python float() will raise ValueError if the passed parameter is not a numeric value. In this example, we passed an alphabet string as the parameter to the float() function.

Python3




number = "geeks"
try:
    print(float(number))
except ValueError as e:
    print(e)


Output:

could not convert string to float: 'geeks'

Python float() OverflowError

float() in Python will raise OverflowError if the passed parameter is too large (ex.: 10**309)

Python3




print(float(10**309))


Output:

Traceback (most recent call last):
  File "/home/1eb6a2abffa536ccb1cae660db04a162.py", line 1, in <module>
    print(float(10**309))
OverflowError: int too large to convert to float


Previous Article
Next Article

Similar Reads

Python | Sort a tuple by its float element
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '14.107'), ('akash', '24.541'), ('anand', '4.256'),
3 min read
Python | Float type and its methods
The float type in Python represents the floating point number. Float is used to represent real numbers and is written with a decimal point dividing the integer and fractional parts. For example, 97.98, 32.3+e18, -32.54e100 all are floating point numbers. Python float values are represented as 64-bit double-precision values. The maximum value any fl
3 min read
Python | Float Layout in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. &#128073;&#127997; Kivy Tutorial - Learn Kivy with Examples. FloatLayout: Floatlayout allows us to place the eleme
5 min read
Python | Filter out integers from float numpy array
Given a numpy array, the task is to filter out integers from an array containing float and integers. Let's see few methods to solve a given task. Method #1 : Using astype(int) C/C++ Code # Python code to demonstrate # filtering integers from numpy array # containing integers and float import numpy as np # initialising array ini_array = np.array([1.
2 min read
Python | Check for float string
One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let's discuss certain ways in which one can check if string is a float to avo
4 min read
Python | sympy.Float() method
With the help of sympy.Float() method, we can convert the integer values to floating point values and by using this method we can also set the values of precision. By default value of precision is 15. Syntax : sympy.Float() Return : Return the floating point number. Example #1 : In this example we can see that by using sympy.Float() method, we can
1 min read
Python | Min/Max value in float string list
Sometimes, while working with a Python list, we can have a problem in which we need to find min/max value in the list. But sometimes, we don't have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let's discuss a way in which this problem
6 min read
Convert Python String to Float datatype
Let us see how to convert a string object into a float object. We can do this by using these functions : float() decimal() Method 1: Using float() # declaring a string str1 = &quot;9.02&quot; print(&quot;The initial string : &quot; + str1) print(type(str1)) # converting into float str2 = float(str1) print(&quot;\nThe conversion of string to float i
2 min read
Display scientific notation as float in Python
In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with "{:e}" to format the number to scientific notation. str.format() formats the num
2 min read
Generate a Vandermonde Matrix of the Legendre Polynomial with Float Array of Points in Python using NumPy
In this article, we will be looking at the approach to generating a Vandermonde matrix of the Legendre polynomial with a float array of points in Python using NumPy. Example: Array: [-1.57 0.58 -3.57 1.44 2.75] Result: [[ 1.000000e+00 -1.570000e+00 3.197350e+00] [ 1.000000e+00 5.800000e-01 4.600000e-03] [ 1.000000e+00 -3.570000e+00 1.861735e+01] [
3 min read
Convert String to Float in Python
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 a String to an integer. Input: "33.28" Output: 33.28 # float Explanation: int in input a
3 min read
ZeroDivisionError: float division by zero in Python
In this article, we will see what is ZeroDivisionError and also different ways to fix this error. What is ZeroDivisionError?A ZeroDivisionError in Python occurs when we try to divide a number by 0. We can't divide a number by 0 otherwise it will raise an error. Let us understand it with the help of an example. In this example, we are dividing a num
2 min read
Check If Value Is Int or Float in Python
In Python, you might want to see if a number is a whole number (integer) or a decimal (float). Python has built-in functions to make this easy. There are simple ones like type() and more advanced ones like isinstance(). In this article, we'll explore different ways to check if a value is an integer or float in Python. To Check If Value Is Int Or Fl
4 min read
How To Fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python
In this article, we'll delve into understanding of typeerror and how to fix "Typeerror: Can'T Convert 'Float' Object To Str Implicitly" In Python. Types of Errors in Python Script ExecutionThere are many different types of errors that can occur while executing a python script. These errors indicate different meanings and are typically classified in
3 min read
Convert String with Comma To Float in Python
When working with data in Python, it's not uncommon to encounter numeric values formatted with a mix of commas and dots as separators. Converting such strings to float is a common task, and Python offers several simple methods to achieve this. In this article, we will explore five generally used methods for converting a string with a comma separato
3 min read
Overflowerror: Convert Int Large to Float in Python
Python overflows when an arithmetic operation yields a number that cannot be represented as a floating point. This happens particularly in the case of very large numbers or complex calculations that go beyond the scope of the Python interpreter. The OverflowError is raised to indicate that the result could not be contained within those constraints.
4 min read
Cannot Convert String To Float in Python
Python, a versatile and powerful programming language, is widely used for data manipulation and analysis. However, developers often encounter challenges, one of which is the "Cannot Convert String To Float" error. This error occurs when attempting to convert a string to a float, but the string's content is incompatible with the float data type. In
3 min read
How to fix AttributeError: module numpy has no attribute float' in Python
While working with the Python NumPy module, you might encounter the error "module 'numpy' has no attribute 'float'". This error arises because numpy's float attribute has been deprecated and removed in favor of using standard Python types. In this article, we will learn how to fix "AttributeError: module 'numpy' has no attribute 'float'". What is A
2 min read
How to Fix "TypeError: list indices must be integers or slices, not float" in Python
Python is a versatile and powerful programming language used in various fields from web development to data analysis. However, like any programming language, Python can produce errors that might seem confusing at first. One such common error is the TypeError: list indices must be integers or slices not float. Understanding this error and knowing ho
4 min read
Convert hex string to float in Python
Converting a hex string to a float in Python involves a few steps since Python does not have a direct method to convert a hexadecimal string representing a float directly to a float. Typically, a hexadecimal string is first converted to its binary representation, and then this binary representation is interpreted as a floating-point number. Convert
3 min read
How to Fix "TypeError: 'float' object is not callable" in Python
In Python, encountering the error message "TypeError: 'float' object is not callable" is a common issue that can arise due to the misuse of the variable names or syntax errors. This article will explain why this error occurs and provide detailed steps to fix it along with the example code and common troubleshooting tips. Understanding the ErrorThe
4 min read
How to convert Float to Int in Python?
Converting a float value to an int is done by Type conversion, which is an explicit method of converting an operand to a specific type. However, it is to be noted that such type of conversion may tend to be a lossy one (loss of data). Converting an int value like 2 to floating-point will result in 2.0, such types of conversion are safe as there wou
6 min read
PyQt5 QSpinBox - Getting float point size | pointSizeF() method
In this article we will see how we can get the floating point size of the text in spin box. Changing the point size will change the size of the text, pixel and point are two different things some point can have multiple pixels inside it. It is recommended to change point size for changing the size of the text. Unlike normal point size, floating poi
2 min read
PyQt5 QSpinBox - Setting float point size | setPointSizeF() method
In this article we will see how we can set the floating-point size of the text in spin box. Changing the point size will change the size of the text, pixel and point are two different things some point can have multiple pixels inside it. It is recommended to change point size for changing the size of the text. Unlike normal point size floating-poin
2 min read
PyQt5 QCalendarWidget - Device Pixel Ratio Float
In this article we will see how we can get device pixel ratio, float value of the QCalendarWidget. The device pixel ratio is the ratio between physical pixels and logical pixels of the calendar. Common values are 1 for normal-dpi displays and 2 for high-dpi “retina” displays, for some devices it is in decimal values like 1.1, 1.2 etc . In order to
2 min read
How to Convert Float to Datetime in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=
3 min read
How to Fix: TypeError: ‘numpy.float’ object is not callable?
In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error: If we try to call a NumPy array as a function, we are most likely to get such an error. Example: C/C++ Code import numpy as np a = np.array([1,2,3]) a() Output: TypeError: 'numpy.ndarray'
1 min read
How to Fix: ValueError: cannot convert float NaN to integer
In this article we will discuss how to fix the value error - cannot convert float NaN to integer in Python. In Python, NaN stands for Not a Number. This error will occur when we are converting the dataframe column of the float type that contains NaN values to an integer. Let's see the error and explore the methods to deal with it. Dataset in use: L
3 min read
Convert 2D float array to 2D int array in NumPy
Converting a 2D float array to a 2D integer array in NumPy is a straightforward process using the astype() method. This conversion can be useful in various data analysis and scientific computing tasks where integer data types are required or where memory efficiency is essential. In this article, we are going to have a look at 'How to convert a 2D f
8 min read
Using NumPy to Convert Array Elements to Float Type
There are often when we must convert an array in Python to a differing type. One of these times would be when given an array and having to convert it to an array of float types. This is often useful when conducting data analysis and there are a variety of ways of doing this. Whilst iterating through the array and using Python's inbuilt float() cast
5 min read
Practice Tags :