English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation de float() en Python et exemples

Python built-in functions

The float() method returns a floating-point number from numbers or strings.

The syntax of float() is:

float([x])

float() parameter

float() method takes one parameter:

  • x (optional)  -The number or string that needs to be converted to a floating-point number.
    If it is a string, then the string should contain a decimal point

Different parameters of float()
Parameter typeUsage
Float numberUsed as float
IntegerUsed as integer
String Must contain decimal digits.
Leading and trailing spaces are removed.
Optional use of “ +”,“-” symbol.
Can include NaN, Infinity, inf (either uppercase or lowercase).

float() return value

float() method returns:

  • Equivalent floating-point number when passing parameters

  • If no parameter is passed, it is 0.0

  • If the parameter is out of the range of Python float, an OverflowError exception will occur

Example1:How does float() work in Python?

# Parameter is integer
print(float(10))
# Parameter is floating
print(float(11.22))
# Parameter is a string float
print(float("-13.33"))
# Parameter is a string with spaces
print(float("     -24.45\n"))
# Parameter is a string, will throw a float error
print(float("abc"))

When running the program, the output is:

10.0
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

Example2:Is float() used for infinity and Nan (not a number)?

# Parameter is NaN
print(float("nan"))
print(float("NaN"))
# Parameter is inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

When running the program, the output is:

nan
nan
inf
inf
inf
inf

Python built-in functions