Python float() Method

Python float() method is a built-in method. It returns a float value from a number or a string. If you pass string argument, it should contain a decimal number.



Parameter Description
x (Optional) This single parameter can be either a number or a string with decimal number.

Return Value

It returns a float value from a number or string.

1.  If the argument is a number or a string, it returns float value.

2.  It returns an error if argument range is outside the float.

3.  It returns 0.0, if argument was not given.

Python float() Method Example

Let’s first understand, how this method works and what does it return?

# integer argument
print("float value:", float(23))
# float argument
print("float value:", float(50.25))
# string argument with decimal number
print("float value:", float("3.8"))
 float value: 23.0
 float value: 50.25
 float value: 3.8

String arguments: What does python say about string arguments in float method?

String arguments must contain numeric digits else it will produce error. See the example below.

# string alphabets argument
print("float value:", float("python"))

 ValueError: could not convert string to float: 'python'

In the below example, it works fine without any error.

# string numeric argument without decimal number
print("float value:", float("38"))
# string numeric argument with decimal number
print("float value:", float("38.5"))
 float value: 38.0
 float value: 38.5

If we don't provide decimal number in string argument, Python set 0 by default. It is recommended by the Python official doc to include decimal number in the argument.