Written by:
1x = 10 2print(float(x)) 3 4#Output -> 10.0
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-presicion value being it´s maximum value 1.8 * 10308.
If the number falls from the limit stablished, it'll return a String with inf
as value.
1x = 1.5 2# -> 1 integer 3# -> .5 fraction 4#-> 1.5 float number
The float()
syntax is quite simple and straight forward.
1float()
Float() will accept any numeric
value (inside it's limit), inf
, infinity
or NaN
and return the floating point value if possible.
Passing a variable
to float()
1x= 5 2print(float(x)) 3#Output -> 5.0
Passing a integer
directly to float()
1print(float(8)) 2#Output -> 8.0
Passing a integer with negative value
directly to float()
1print(float(-55)) 2#Output -> -55.0
Passing a string with a numeric values
to float()
1str = '35' 2print(float(str)) 3#Output -> 35.0
Passing a string with white spaces
to float()
1str = ' 35 ' 2print(float(str)) 3#Output -> 35.0
Passing a boolean
type to float()
1bol = True 2print(float(bol)) 3#Output -> 1.0
Booleans 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()
1print(float(InF)) 2#Output -> inf
Passing nan
to float()
1print(float(nan)) 2#Output -> nan
Passing a string with mixed numeric and non numeric values
to float()
1print(float('4 Geeks Academy')) 2#Output -> Traceback (most recent call last): 3# File "main.py", line 1, in <module> 4# print(float('4 Geeks Academy')) 5# ValueError: could not convert string to float: '4 Geeks Academy'
Passing a value outside the limit causing overflow error
to float()
1print(float(10**432)) 2#Output -> Traceback (most recent call last): 3# File "main.py", line 1, in <module> 4# print(float(10**432)) 5# OverflowError: int too large to convert to float
To learn to Code with Python take a look at our Courses in 4Geeks. Hope you enjoyed the reading and keep on the Geek side!