Short answer: In Python, a float is a data type that stores real numbers with a fractional part, such as 1.5, as a 64-bit double-precision value with a maximum of about 1.8 × 10^308. The built-in float() function converts integers, numeric strings, booleans, 'inf' and 'nan' to floats; for example, float(10) returns 10.0.
x = 10
print(float(x))
#Output -> 10.0What is a Float in Python?
Float is a type of variable present in all programming languages that it´s used to store real numbers with fractions (or floating point numbers). Based on this, we can differentiate in it's composition an Integer type number separated by a . (dot) from the fractional parts. It´s represented as a 64-bit double-precision value whose maximum is about 1.8 * 10308.
If a float goes beyond that limit, Python represents it as inf (infinity), while converting an integer that is too large raises an OverflowError (see the last example).
x = 1.5
# -> 1 integer
# -> .5 fraction
#-> 1.5 float numberSyntax
The float()syntax is quite simple and straight forward.
float()Float() will accept any numeric value (inside it's limit), inf, infinity or NaN and return the floating point value if possible.
Using float() with different types of data
Passing a variable to float()
x= 5
print(float(x))
#Output -> 5.0Passing a integer directly to float()
print(float(8))
#Output -> 8.0Passing a integer with negative value directly to float()
print(float(-55))
#Output -> -55.0Passing a string with a numeric values to float()
text = '35'
print(float(text))
#Output -> 35.0Passing a string with white spaces to float()
text = ' 35 '
print(float(text))
#Output -> 35.0Passing a boolean type to float()
bol = True
print(float(bol))
#Output -> 1.0Booleans can have 2 possible values, 1 for True and 0 for False, that´s why if received True float() returns 1.0
Passing 'inf' to float()
print(float('inf'))
#Output -> infPassing 'nan' to float()
print(float('nan'))
#Output -> nanPassing a string with mixed numeric and non numeric values to float()
print(float('4 Geeks Academy'))
#Output -> Traceback (most recent call last):
# File "main.py", line 1, in <module>
# print(float('4 Geeks Academy'))
# ValueError: could not convert string to float: '4 Geeks Academy'Passing a value outside the limit causing overflow error to float()
print(float(10**432))
#Output -> Traceback (most recent call last):
# File "main.py", line 1, in <module>
# print(float(10**432))
# OverflowError: int too large to convert to floatTo learn to Code with Python take a look at our Courses in 4Geeks. Hope you enjoyed the reading and keep on the Geek side!
Understanding how float() converts values, and when it raises errors, is part of writing reliable Python code. To keep building these skills step by step, you can learn to code in a program with projects and mentors.
