Python float() method


float() function is used to convert integers and strings to floating-point numbers. If you want to convert from another data type to the flaot data type, you can use float().

To see the data type of a variable or value just call type()

>>> x = 3
>>> y = 5.6
>>> type(x)
<class 'int'>
>>> type(y)
<class 'float'>

Related course: Complete Python Programming Course & Exercises

syntax

Float() method syntax.

class float([x])

parameters

  • x -- integer or string

return value

Returns floating point numbers.

Python float() example

The following examples demonstrate how float() can be used.

>>> float(1)
1.0
>>> float(112)
112.0
>>> float(-123.6)
-123.6
>>> float('123') # string
123.0

The following example shows how to use the float() function from a Python script:

print(float(1))
print(float(15))
print(float(-15.3))
print(float('568')) # string

output

1.0
15.0
-15.3
568.0

Conversion of decimal integers to decimal floating-point numbers

>>> float(5)
5.0
>>> float(-6)
-6.0

Conversion of decimal strings to decimal floating-point points

>>> float('24.5')
24.5
>>> float('-905.4')
-905.4

Conversion of Boolean values to floating-point numbers

In Python, the Boolean equals 1.0 and 0.0 in the calculation:

>>> float(True)
1.0
>>> float(False)
0.0

python float method

Note

It is also possible to convert floating-point points to floating-point points, which would not make any sense and would be error-free.

>>> float(3.42)
3.42
>>> float(-2.33)
-2.33
>>> float(2e3)
2000.0

Error when a non-decimal string is used as an argument, exceeding a numeric character

>>> float('2a1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '2a1'

Value error: cannot convert string '2a1' to floating point.

the float function cannot be converted in arbitrary binary like the int function

For example, when trying to convert the binary number 11 to decimal floating point 3.0, an error is reported.

>>> float(11, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float() takes at most 1 argument (2 given)

Type error: the float function has at most one parameter (2 parameters given). returns 0.0 when all parameters are omitted

>>> float()
0.0