float() in Python

• Difficulty Level : Easy
• Last Updated : 17 Sep, 2021

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

Syntax:  float(x)

float() Parameters

The method only accepts one parameter and that is also optional to use. Let us look at the various types of argument, the method accepts:

A number: Can be an integer or a floating-point number.

A String :

• Must contain numbers of any type.
• Any left or right whitespaces or a new line is ignored by the method.
• Mathematical Operators can be used.
• Can contain NaN, Infinity or inf (any cases)

Values that the 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.

Python3

 # Python program to illustrate# Various examples and working of float()# for integersprint(float(21.89)) # for floating point numbersprint(float(8)) # for integer type stringsprint(float("23")) # for floating type stringsprint(float("-16.54")) # for string floats with whitespacesprint(float("     -24.45   \n")) # for inf/infinityprint(float("InF"))print(float("InFiNiTy")) # for NaNprint(float("nan"))print(float("NaN")) # Error is generated at lastprint(float("Geeks"))

Output:

21.89
8.0
23.0
-16.54
-24.45
inf
inf
nan
nan

All lines are executed properly but the last one will return an error:

Traceback (most recent call last):
File "/home/21499f1e9ca207f0052f13d64cb6be31.py", line 25, in
print(float("Geeks"))
ValueError: could not convert string to float: 'Geeks'

Python3

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

Output:

inf
inf
nan
nan

Python3

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

Output:

90.0

Python3

 # python code to convert string# to floatstring = "90"result = float(string) print(result)

Output:

90.0

Python3

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

Output:

could not convert string to float: 'geeks'

My Personal Notes arrow_drop_up